call()
call() 方法调用一个函数, 其具有一个指定的this值和分别地提供的参数(参数的列表)。
语法:
function.call(thisArg, arg1, arg2, ...)
参数:
thisArg:可选的。表示this修改后指向的目标。(注意:如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。)
arg1:,arg2可选的。表示函数的参数列表,表示哪些函数的属性会继承过去。
例子:
function Product(name, price) { this.name = name; this.price = 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);
其他例子:
对匿名函数上使用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); }