fun.apply(thisArg,[argsArray])
fun.call(thisArg[, arg1[, arg2[, ...]]])
两者的用法很相近,实现的功能是将某一方法fun或者某一对象内部的某个方法fun应用在另一个对象thisArg上,并且避免重复定义这个要用的方法,原理是为要调用的那个方法fun中的this指定为需要这个方法的对象。两者最主要的区别是apply接受的参数是a single array of arguments,而call接受的参数是an argument list。
apply()
下面例子将Math中的max方法应用在number数组上,获得数组中的最大值。
var numbers = [5, 6, 2, 3, 7]; var max = Math.max.apply(null, numbers); //null也可以写成{},这里不能使用call,因为numbers是一个数组 // This about equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...)
下面这个例子将apply用于构造函数
Function.prototype.construct = function(aArgs) { var fConstructor = this, fNewConstr = function() { fConstructor.apply(this, aArgs); }; fNewConstr.prototype = fConstructor.prototype; return new fNewConstr(); }; function MyConstructor() { for (var nProp = 0; nProp < arguments.length; nProp++) { this['property' + nProp] = arguments[nProp]; } } var myArray = [4, 'Hello world!', false]; var myInstance = MyConstructor.construct(myArray); console.log(myInstance.property0 + ',' + myInstance.property1 + ',' + myInstance.property2); // logs "4,Hello world!,false" console.log(myInstance instanceof MyConstructor); // logs 'true' console.log(myInstance.constructor); // logs 'MyConstructor'
call()
下面这个例子示意了call的基本用法,为方法greet()中的this指定为对象ifunction greet() { var reply = [this.person, 'Is An Awesome', this.role].join(' '); console.log(reply); } var i = { person: 'Douglas Crockford', role: 'Javascript Developer' }; greet.call(i);
下面这个例子示意了利用call()调用了匿名函数。
var animals = [ { species: 'Lion', name: 'King' }, { species: 'Whale', name: 'Fail' } ]; for (var i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); }
下面这个例子示意了call()在构造函数中的应用。
function Product(name, price) { this.name = name; this.price = price; if (price < 0) { throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } function Toy(name, price) { Product.call(this, name, price); this.category = 'toy'; } var cheese = new Food('feta', 5); var fun = new Toy('robot', 40); console.log(cheese);//Food {name: "feta", price: 5, category: "food"} console.log(fun);//Toy {name: "robot", price: 40, category: "toy"}