Function.prototype.call()
call()方法使用一个指定的this值和单独给出的一个或者多个参数来调用一个函数。
call()方法接受的是一个参数列表。
call()代码示例
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
语法
function.call(thisArg, arg1, arg2, ...)
参数
thisArg
该参数是可选的,在函数运行时使用的 this 值。但是,this可能不是该方法看到的实际值,如果这个函数处于 非严格模式下,则指定为 null 或者 undefined 会自动替换为指向全局对象,原始值会被包装。
arg1,arg2,···
指定的参数列表。
返回值
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
描述
call() 允许为不同的对象分配和调用属于一个对象的函数or方法。
call() 提供的新 this 值给它当桥调用的函数or方法。可以使用 call 实现继承,写一个方法,然后让另一个新的对象来继承它。
call()用法
使用 call 方法调用父构造函数
代码示例
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);
该段代码中,Food 和 Toy 构造函数创建的对象实例都会拥有在Product 函数中添加的name 和 price 属性,但是category 属性实在各自的构造函数中定义的。
使用 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);
}
该段代码中,构造了匿名函数function(i),然后它通过调用该函数的call 方法将每个数组元素animals[i]作为指定的this 执行该匿名函数。
使用 call 方法调用函数并且指定上下文的 'this'
function greet() {
var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
console.log(reply);
}
var obj = {
animal: 'cats', sleepDuration: '12 and 16 hours'
};
greet.call(obj); // cats typically sleep between 12 and 16 hours
该段代码中,把 obj 作为指定的 this 传到 greet 函数中。
使用 call() 方法调用函数并且不指定第一个参数
非严格模式代码示例
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // sData value is Wisen
由于使用 call 方法的时候并没有在里面设置第一个参数,所以这里的this 会被绑定为全局对象 window.sData 。
严格模式代码示例
'use strict';
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // Cannot read the property of 'sData' of undefined
严格模式下,this 的值会是 undefined ,因此没有this.sData 对象。