JavaScript中call和apply的用法与区别

call和apply的用法

例子

function Car(color,size) {
   
	this.color = color;
	this.size = size;
}
function SmallCar(color,size,date) {
   
	Car.call(this,color,size);
	this.date = date;
}
var car = new SmallCar('blue',12,23);


在new的时候,SmallCar方法中的this指向car,然后通过Car.call()方法改变Car方法中的this指向,让Car方法中的this指向car,而apply的用法与call相同但是传参形式不同,如下

function Car(color,size) {
   
	this.color = color;
	this.size = size;
}
function SmallCar(color,size,date) {
   
	Car.apply(this,[color,size]);
	this.date = date;
}
var car = new SmallCar('blue',12,23);

总结

call和apply的作用就是改变this的指向,区别就是传参形式不同。

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务