面向对象的JavaScript-008-Function介绍

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();

 

posted @ 2016-05-24 17:04  shamgod  阅读(312)  评论(0编辑  收藏  举报
haha