面向对象的JavaScript-006-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();

时间: 2024-10-23 04:52:38

面向对象的JavaScript-006-Function介绍的相关文章

用面向对象的Javascript来介绍一下自己

看了一道题目<用面向对象的Javascript来介绍一下自己>,然后自己觉得挺好玩的,所以就编写如下的代码. // HELPER function extend(sup, overrides) { var sub = overrides && overrides.constructor || function() { sup.apply(this, arguments); }; var fn = function() {}; var subp; fn.prototype = n

javascript中function和object的区别,以及javascript如何实现面向对象的编程思想.

1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5 <title></title> 6 <script language="

全面理解面向对象的JavaScript

转载:http://justcoding.iteye.com/blog/2019293 原文:http://www.ibm.com/developerworks/cn/web/1304_zengyz_jsoo/index.html?ca=drs-#major6 前言 当今 JavaScript 大行其道,各种应用对其依赖日深.web 程序员已逐渐习惯使用各种优秀的 JavaScript 框架快速开发 Web 应用,从而忽略了对原生 JavaScript 的学习和深入理解.所以,经常出现的情况是,

( 译、持续更新 ) JavaScript小技巧介绍

感谢好友破狼提供的这篇好文章,也感谢写这些知识点的作者们和将他们整理到一起的作者.这是github上的一篇文章,在这里本兽也就只做翻译,由于本兽英语水平和编程能力都不咋地,如有不好的地方也请多理解体谅.原文 能够为大家提供这些简短而实用的JavaScript技巧来提高大家编程能力,这对于我来说是件很开心的事.每天仅花上不到2分钟的时间中,你将可以读遍JavaScript这门可怕的语言所呈现给我们的特性:performance(性能), conventions(协议), hacks(代码hack)

深入全面理解面向对象的 JavaScript

深入全面理解面向对象的 JavaScript (原著: 曾 滢, 软件工程师, IBM,2013 年 4 月 17 日) JavaScript 函数式脚本语言特性以及其看似随意的编写风格,导致长期以来人们对这一门语言的误解,即认为 JavaScript 不是一门面向对象的语言,或者只是部分具备一些面向对象的特征.本文将回归面向对象本意,从对语言感悟的角度阐述为什么 JavaScript 是一门彻底的面向对象的语言,以及如何正确地使用这一特性. 前言 当今 JavaScript 大行其道,各种应用

JavaScript prototype 使用介绍

JavaScript prototype 使用介绍 用过JavaScript的同学们肯定都对prototype如雷贯耳,但是这究竟是个什么东西却让初学者莫衷一是,只知道函数都会有一个prototype属性,可以为其添加函数供实例访问,其它的就不清楚了,最近看了一些 JavaScript高级程序设计,终于揭开了其神秘面纱 用过JavaScript的同学们肯定都对prototype如雷贯耳,但是这究竟是个什么东西却让初学者莫衷一是,只知道函数都会有一个prototype属性,可以为其添加函数供实例访

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

JavaScript Oriented 探究面向对象的JavaScript高级语言特性 Prologue . JavaScript Introduce 1.  JS Abstract JavaScript是由Netscape公司工程师Brendan Eich研发的脚本语言,经过推广和流行,兼容ECMA-262标准,至今用于描述HTML网页行为.(前端验证,检测,响应,触发,控制等动态行为) Knowledge Tree 2.     About Document 本文涉及到的概念有JavaScr

从面向对象看JavaScript(一)

前言 JavaScript作为一种脚本语言,语法简单(求其),易上手,适合开发:同时,作为当今前端编程方面占据垄断地位,甚至逐步向后端发展的强势语言,它的前景十分美好,功能足够强大.既然是脚本语言,自然没有c,c++,Java等传统语言的严谨,但是利用它仍然可以基本覆盖其他语言能做到的高级功能. 下面我就从面向对象的角度,整合JavaScript里函数,对象,引用类型,原型,闭包,作用域链等知识点,去探讨JavaScript是如何定义对象,构造类,设置属性和函数的私有公有权限,实现继承,利用作用

全面理解面向对象的 JavaScript

对象的上下文依赖 var str = "我是一个 String 对象 , 我声明在这里 , 但我不是独立存在的!" var obj = { des: "我是一个 Object 对象 , 我声明在这里,我也不是独立存在的." }; var fun = function() { console.log( "我是一个 Function 对象!谁调用我,我属于谁:", this ); }; obj.fun = fun; console.log( this

前端开发:面向对象与javascript中的面向对象实现(一)

前端开发:面向对象与javascript中的面向对象实现(一) 前言: 人生在世,这找不到对象是万万不行的.咱们生活中,找不到对象要挨骂,代码里也一样.朋友问我说:“嘿,在干嘛呢......”,我:“找不到对象!”,他:“就你那样也能找得到对象?”.我一脸黑线...... 废话不多说,今天博主要跟大家聊的是<面向对象与javascript中的面向对象实现>”. 面向对象理解: 面向对象是一种对现实世界理解和抽象的方法,是一种先进的程序设计理念,是一种比较抽象的,多形态的设计模式.我们可以这么理