javascript中call的用法总结
1.使用call方法调用函数并且指定上下文的’this’
function greet(){
console.log(this.name+",age="+this.age)
}
greet.call({name:'lihh',age:24});//输出:lihh,age=24
可以看出greet.call中的{name:‘lihh’,age:24}就是greet()中的this
2.使用call方法调用匿名函数
下边是来自MDN的一个例子
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);
}
运行结果为#0 Lion: King
#1 Whale: Fail
可以看出的是:a.第一个animals[i] 替代了this,第二个i则是传递进去了参数
3.使用call方法调用父构造函数
MDN上的例子有点没看懂,所以改造了一下,在Food中打印一下this,看看要替代的到底是什么
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) {
console.log('---');
console.log(this);
console.log('---');
//Product.call(this, name, price);
this.category = 'food';
}
然后new Food(‘青椒’,9),结构如下
//—
// Food(){}
// category:“food”
// proto:Object
//—
有点蒙,我的理解是Product.call(this, name, price);这句代码中的this是function Food(name, price) {},用此来替换Product中this的指向,name和price则用来给Product传递参数
4.总结以上三点,借鉴MDN的说明:
- call的用法为func.call(thisArg,args…),thisArg用来替代func中的this指向,args则是给func设置参数
- 3的做法似乎是一种喧宾夺主的做法,把Product中this改为Food的指向,从而达到子类继承父类的做法