1.

  1 // 函数
  2     /* Declare the function 'myFunc' */
  3     function myFunc(theObject) {
  4        theObject.brand = "Toyota";
  5      }
  6
  7      /*
  8       * Declare variable 'mycar';
  9       * create and initialize a new Object;
 10       * assign reference to it to 'mycar'
 11       */
 12      var mycar = {
 13        brand: "Honda",
 14        model: "Accord",
 15        year: 1998
 16      };
 17
 18      /* Logs 'Honda' */
 19      console.log(mycar.brand);
 20
 21      /* Pass object reference to the function */
 22      myFunc(mycar);
 23
 24      /*
 25       * Logs 'Toyota' as the value of the 'brand' property
 26       * of the object, as changed to by the function.
 27       */
 28      console.log(mycar.brand);
 29
 30      //var y = function x() {};
 31      //alert(x); // throws an error
 32     //var foo = new Function("alert(anonymous);");
 33     //foo();    //Uncaught ReferenceError: anonymous is not defined
 34     foo(); // alerts FOO!
 35     function foo() {
 36        alert('FOO!');
 37     }
 38     var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
 39     foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
 40
 41     var x = 0;               // source element
 42     if (x == 0) {            // source element
 43        x = 10;               // not a source element
 44        function boo() {}     // not a source element
 45     }
 46     function foo() {         // source element
 47        var y = 20;           // source element
 48        function bar() {}     // source element
 49        while (y == 10) {     // source element
 50           function blah() {} // not a source element
 51           y++;               // not a source element
 52        }
 53     }
 54
 55     // function declaration
 56     function foo() {}
 57
 58     // function expression
 59     (function bar() {})
 60
 61     // function expression
 62     x = function hello() {}
 63
 64
 65     if (x) {
 66        // function expression
 67        function world() {}
 68     }
 69
 70
 71     // function declaration
 72     function a() {
 73        // function declaration
 74        function b() {}
 75        if (0) {
 76           // function expression
 77           function c() {}
 78        }
 79     }
 80
 81     // This function returns a string padded with leading zeros
 82     function padZeros(num, totalLen) {
 83        var numStr = num.toString();             // Initialize return value as string
 84        var numZeros = totalLen - numStr.length; // Calculate no. of zeros
 85        for (var i = 1; i <= numZeros; i++) {
 86           numStr = "0" + numStr;
 87        }
 88        return numStr;
 89     }
 90     var result;
 91     result = padZeros(42,4); // returns "0042"
 92     console.log(result);
 93     result = padZeros(42,2); // returns "42"
 94     console.log(result);
 95     result = padZeros(5,4);  // returns "0005"
 96     console.log(result);
 97
 98     // 菲波那其数
 99     var factorial = function fac(n) { return n<2 ? 1 : n*fac(n-1) };
100     console.log(factorial(3));
101
102     function map(f,a) {
103       var result = [], // Create a new Array
104           i;
105       for (i = 0; i != a.length; i++)
106         result[i] = f(a[i]);
107       return result;
108     }
109     console.log(map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]));    // returns [0, 1, 8, 125, 1000].
110
111     // 阶乘
112     function factorial(n){
113       if ((n === 0) || (n === 1))
114         return 1;
115       else
116         return (n * factorial(n - 1));
117     }
118     var a, b, c, d, e;
119     a = factorial(1); // a gets the value 1
120     b = factorial(2); // b gets the value 2
121     c = factorial(3); // c gets the value 6
122     d = factorial(4); // d gets the value 24
123     e = factorial(5); // e gets the value 120
124     console.log(a);
125     console.log(b);
126     console.log(c);
127     console.log(d);
128     console.log(e);
129
130     // Function scope
131     // The following variables are defined in the global scope
132     var num1 = 20,
133         num2 = 3,
134         name = "Chamahk";
135
136     // This function is defined in the global scope
137     function multiply() {
138       return num1 * num2;
139     }
140
141     multiply(); // Returns 60
142
143     // A nested function example
144     function getScore () {
145       var num1 = 2,
146           num2 = 3;
147
148       function add() {
149         return name + " scored " + (num1 + num2);
150       }
151
152       return add();
153     }
154
155     console.log(getScore()); // Returns "Chamahk scored 5"
156
157     var x = 0;
158     while (x < 10) { // "x < 10" is the loop condition
159        // do stuff
160        x++;
161     }
162
163     // can be converted into a recursive function and a call to that function:
164     function loop(x) {
165       if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
166         return;
167       // do stuff
168       loop(x + 1); // the recursive call
169     }
170     loop(0);
171
172     // However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:
173     function walkTree(node) {
174       if (node == null) //
175         return;
176       // do something with node
177       for (var i = 0; i < node.childNodes.length; i++) {
178         walkTree(node.childNodes[i]);
179       }
180     }
181
182     // function foo(i) {183     //   if (i < 0)
184     //     return;
185     //   console.log('begin:' + i);
186     //   foo(i - 1);
187     //   console.log('end:' + i);
188     // }
189     //foo(3);
190     // Output:
191
192     // begin:3
193     // begin:2
194     // begin:1
195     // begin:0
196     // end:0
197     // end:1
198     // end:2
199     // end:3
200
201     // Nested functions and closures
202     function addSquares(a,b) {
203       function square(x) {
204         return x * x;
205       }
206       return square(a) + square(b);
207     }
208     a = addSquares(2,3); // returns 13
209     b = addSquares(3,4); // returns 25
210     c = addSquares(4,5); // returns 41
211
212     // Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
213
214     function outside(x) {
215       function inside(y) {
216         return x + y;
217       }
218       return inside;
219     }
220     fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
221     result = fn_inside(5); // returns 8
222
223     result1 = outside(3)(5); // returns 8
224
225     // Multiply-nested functions
226     function A(x) {
227       function B(y) {
228         function C(z) {
229           console.log(x + y + z);
230         }
231         C(3);
232       }
233       B(2);
234     }
235     A(1); // logs 6 (1 + 2 + 3)
236
237     // Name conflicts
238     function outside() {
239       var x = 10;
240       function inside(x) {
241         return x;
242       }
243       return inside;
244     }
245     result = outside()(20); // returns 20 instead of 10
246
247     // Closures
248     var pet = function(name) {   // The outer function defines a variable called "name"
249       var getName = function() {
250         return name;             // The inner function has access to the "name" variable of the outer function
251       }
252       return getName;            // Return the inner function, thereby exposing it to outer scopes
253     },
254     myPet = pet("Vivie");
255
256     myPet();                     // Returns "Vivie"
257
258     var createPet = function(name) {
259       var sex;
260
261       return {
262         setName: function(newName) {
263           name = newName;
264         },
265
266         getName: function() {
267           return name;
268         },
269
270         getSex: function() {
271           return sex;
272         },
273
274         setSex: function(newSex) {
275           if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) {
276             sex = newSex;
277           }
278         }
279       }
280     }
281
282     var pet = createPet("Vivie");
283     pet.getName();                  // Vivie
284
285     pet.setName("Oliver");
286     pet.setSex("male");
287     pet.getSex();                   // male
288     pet.getName();                  // Oliver
289
290     var getCode = (function(){
291       var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
292
293       return function () {
294         return secureCode;
295       };
296     })();
297
298     getCode();    // Returns the secureCode
299
300     var createPet = function(name) {  // Outer function defines a variable called "name"
301       return {
302         setName: function(name) {    // Enclosed function also defines a variable called "name"
303           name = name;               // ??? How do we access the "name" defined by the outer function ???
304         }
305       }
306     }
307
308     // Using the arguments object
309     function myConcat(separator) {
310        var result = "", // initialize list
311            i;
312        // iterate through arguments
313        for (i = 1; i < arguments.length; i++) {
314           result += arguments[i] + separator;
315        }
316        return result;
317     }
318
319     // returns "red, orange, blue, "
320     myConcat(", ", "red", "orange", "blue");
321
322     // returns "elephant; giraffe; lion; cheetah; "
323     myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
324
325     // returns "sage. basil. oregano. pepper. parsley. "
326     myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
327
328     // Default parameters
329     function multiply(a, b) {
330       b = typeof b !== 'undefined' ?  b : 1;
331
332       return a*b;
333     }
334
335     multiply(5); // 5
336
337     // function multiply2(a, b = 1) {338     //   return a*b;
339     // }
340
341     // multiply2(5); // 5
342
343     // Rest parameters
344     // function multiply(multiplier, ...theArgs) {345     //   return theArgs.map(x => multiplier * x);
346     // }
347
348     // var arr = multiply(2, 1, 2, 3);
349     // console.log(arr); // [2, 4, 6]
350
351     // Arrow functions
352     var a = [
353       "Hydrogen",
354       "Helium",
355       "Lithium",
356       "Beryl­lium"
357     ];
358
359     var a2 = a.map(function(s){ return s.length });
360
361     // var a3 = a.map( s => s.length );
362
363     // Lexical this
364
365     function Person() {
366       // The Person() constructor defines `this` as itself.
367       this.age = 0;
368
369       setInterval(function growUp() {
370         // In nonstrict mode, the growUp() function defines `this`
371         // as the global object, which is different from the `this`
372         // defined by the Person() constructor.
373         this.age++;
374       }, 1000);
375     }
376
377     var p = new Person();
378
379     function Person() {
380       var self = this; // Some choose `that` instead of `self`.
381                        // Choose one and be consistent.
382       self.age = 0;
383
384       setInterval(function growUp() {
385         // The callback refers to the `self` variable of which
386         // the value is the expected object.
387         self.age++;
388       }, 1000);
389     }
390
391     // function Person(){392     //   this.age = 0;
393
394     //   setInterval(() => {395     //     this.age++; // |this| properly refers to the person object
396     //   }, 1000);
397     // }
398
399     // var p = new Person();

转载于:https://www.cnblogs.com/shamgod/p/5524082.html

面向对象的JavaScript-008-Function介绍相关推荐

  1. (转)面向对象的 JavaScript 编程:dojo.declare 详解

    >>>>>http://www.ibm.com/developerworks/cn/<<<<< JavaScript 早在发明初期时,仅用来 ...

  2. 面向对象的JavaScript编程

    面向对象的JavaScript编程     Javascript对于做过Web程序的人不应该是陌生,初期是用来做一些简单的FORM验证,基本上是在玩弄一些技巧性的东西.IE 4.0引入了DHTML,同 ...

  3. JavaScript Oriented[探究面向对象的JavaScript高级语言特性]

    JavaScript Oriented 探究面向对象的JavaScript高级语言特性 Prologue . JavaScript Introduce 1.  JS Abstract JavaScri ...

  4. (自己收藏)全面理解面向对象的 JavaScript

    全面理解面向对象的 JavaScript 前天 by 资深编辑 WnouM 评论(3) 有2727人浏览 收藏 javascript 面向对象 对象 类 原型 < >猎头职位: 上海:Ju ...

  5. 面向对象的 JavaScript 编程及其 Scope 处理

    为什么80%的码农都做不了架构师?>>>    在面向对象的 JavaScript 编程中,我们常常会将一些数据结构和操作封装成对象以达到继承和重用的目的.然而层层封装和继承再加上 ...

  6. JavaScript内核系列 第8章 面向对象的JavaScript(下)

    原创作者: abruzzi 接上篇:JavaScript内核系列 第8章 面向对象的JavaScript(上) 8.4实例:事件分发器 这一节,我们通过学习一个面向对象的实例来对JavaScript的 ...

  7. 谈谈JavaScript中function多重理解

    JavaScript 中的 function 有多重意义.它可能是一个构造器(constructor),承担起对象模板的作用: 可能是对象的方法(method),负责向对象发送消息.还可能是函数,没错 ...

  8. 如何用mshtml获得Javascript中function的返回值[mshtml]

    marginwidth="0" marginheight="0" src="http://218.16.120.35:65001/PC/Global/ ...

  9. JavaScript prototype 使用介绍

    JavaScript prototype 使用介绍用过JavaScript的同学们肯定都对prototype如雷贯耳,但是这究竟是个什么东西却让初学者莫衷一是,只知道函数都会有一个prototype属 ...

  10. 面向对象的 JavaScript:封装、继承与多态

    本文作者:家园工作室研发组成员 @维尔希宁 本文出处: 面向对象的 JavaScript:封装.继承与多态​blog.lenconda.top 本文遵循署名-非商业性使用-禁止演绎3.0 未本地化版本 ...

最新文章

  1. v-model 使用场景和源码学习
  2. FCKeditor 在ASP.Net 中的使用说明
  3. java 数据分析库_超级好用的 Java 数据可视化库:Tablesaw
  4. delphi 鼠标获取窗口句柄_Windows窗口自定义,只需WindowTop一键设置
  5. 计算机web程序开发,基于WEB的计算机应用基础考试系统的开发与设计
  6. C++之保护和私有构造函数与析构函数
  7. 镜像miracast投屏软件_miracast投屏软件下载
  8. android版 wifi伴侣,wifi伴侣下载|wifi伴侣安卓版2016最新版 3.7.5 - 系统天堂
  9. 接口测试通用测试用例
  10. c语言 统计素数并求和
  11. Windows 技巧集
  12. T229473 D. 背单词的小智 (二分
  13. 关于 nscd,nslcd 和 sssd 套件的综述
  14. 编译提示“/usr/bin/ld: cannot find -lgflags-shared“错误的解决办法
  15. 游戏引擎 白鹭(egret)学习总结(一)
  16. 盘点适合入门学习的C/C++开源项目
  17. android串口通信——android-serialport-api
  18. Google 搜索的运作方式
  19. Notice: Use of undefined constant MCRYPT_RIJNDAEL_128 - assumed ‘MCRYPT_RIJNDAEL_128‘ in
  20. 课程设计:转速、电流双闭环调速系统设计及仿真

热门文章

  1. php的json_encode第二个参数学习及应用
  2. Java基础梳理(一)
  3. 打乱一个排好序的 list 对象 alist?
  4. ecstore 定时任务配置
  5. 同步互斥阻塞 (2)
  6. [CQOI2009][BZOJ1303] 中位数图
  7. NEC学习 ---- 布局 -两列, 右侧定宽,左侧自适应
  8. Dictionary Union and Sort by value
  9. MySQL中 slave_compressed_protocol=ON 的压缩效果实验
  10. Python搭建简易HTTP服务(3.x版本和2.x版本的)