Chapter 4. Functions
4.1函数对象
对象有连到原型的隐藏连接,函数对象连接到Function.prototype。
函数在创建时带有prototype属性,它的值是一个有constructor属性且constructor的值就是函数值本身的对象。
1 var func = function() {};//GC查看func的属性
4.2函数字面量
var add = function (a, b) { return a + b; };
4.3调用
javascript有四种调用函数的方式。调用函数时会传入两个参数this和arguments。
4.3.1方法调用模式
当函数作为一个对象的属性时叫方法。方法调用时this指向该对象。
var myObject = { value: 0; increment: function (inc) { this.value += typeof inc === 'number' ? inc : 1; } }; myObject.increment( ); document.writeln(myObject.value); // 1 myObject.increment(2); document.writeln(myObject.value); // 3
4.3.2函数调用模式
当一个函数并非一个对象属性时,它被当作函数调用。
var sum = add(3, 4); // sum is 7
这时this指向全局变量,需要靠一个变量来传值。
// Augment myObject with a double method. myObject.double = function ( ) { var that = this; // Workaround. var helper = function ( ) { that.value = add(that.value, that.value) }; helper( ); // Invoke helper as a function. }; // Invoke double as a method. myObject.double( ); document.writeln(myObject.getValue( )); // 6
4.3.3构造器调用模式
如果在函数前加个new,那么将创建一个连接到该函数prototype属性的新对象,同时this指向新对象。
// Create a constructor function called Quo. // It makes an object with a status property. var Quo = function (string) { this.status = string; }; // Give all instances of Quo a public method // called get_status. Quo.prototype.get_status = function ( ) { return this.status; }; // Make an instance of Quo. var myQuo = new Quo("confused"); document.writeln(myQuo.get_status( )); // confused
4.3.4Apply模式调用
其实就是apply函数的运用。
// Make an array of 2 numbers and add them. var array = [3, 4]; var sum = add.apply(null, array); // sum is 7 // Make an object with a status member. var statusObject = { status: 'A-OK' }; // statusObject does not inherit from Quo.prototype, // but we can invoke the get_status method on // statusObject even though statusObject does not have // a get_status method. var status = Quo.prototype.get_status.apply(statusObject); // status is 'A-OK'