JavaScript中的apply和call

刚刚接触到apply和call方法时,对他们两个的理解十分的模糊,最近在联系的过程中对apply和call有了更清晰的理解了,我把我对这个问题的理解记录在这里,如果有什么不对的或者说的不清楚的地方还请大家指出,谢谢


1.apply   

apply的语法:Function.apply(obj, args)
apply可以用另一个对象代替当前对象。
apply方法有两个参数:
obj:这个对象将代替function里的this对象
args:是一个数组,会作为参数传递给function
如果没有提供obj参数,那么Global对象将作用于obj
function Fruit(season, time, weight){
	this.season = season;
	this.time = time;
	this.weight = weight;
	this.showMessage = function(){
		console.log(this.season);
		console.log(this.time);
		console.log(this.weight);
	}
}

function Apple(season, time, weight, size){
	Fruit.apply(this, arguments);
	this.size = size;
	this.showMessage = function(){
		console.log(this.season);
		console.log(this.time);
		console.log(this.weight);
		console.log(this.size);
	} 

}

var grape = new Fruit('spring', 'June', 34);
grape.showMessage();
console.log('\n');
var apple = new Apple('spring', 'September', 44, 'big');
apple.showMessage();
结果:


分析:
当一开始创建Apple类时,this指向的是Apple,后来程序运行到apply语句,this代替Fruit中的对象,即用Apple去执行Fruit的内容,这样,Fruit类中的season,time,weight属性就成功创建到了Apple类中。

2.call

call和apply意思一样,除了参数列表的不同。
call的语法:Function(this,参数列表)
举个例子,对钢材的代码稍加改动
function Fruit(season, time, weight){
	this.season = season;
	this.time = time;
	this.weight = weight;
	this.showMessage = function(){
		console.log(this.season);
		console.log(this.time);
		console.log(this.weight);
	}
}

function Apple(season, time, size){
	Fruit.call(this, season, time, size);
	this.size = size;
	this.showMessage = function(){
		console.log(this.season);
		console.log(this.time);
		console.log(this.size);
	} 

}

var grape = new Fruit('spring', 'June', 34);
grape.showMessage();
console.log('\n');
var apple = new Apple('spring', 333, 'small');
apple.showMessage();




3.两者之间的区别

用apply时,传递的参数为arguments,参数类型为数组,参数列表是一一对应的,也就是说arguments的前几位和Fruit中的参数完全相同,而运用call方法时,参数是可以选择的,我们可以根据需求来写参数,在上面的例子中我们可以看到,我们所需要的参数只有season和call,在这种情况下,这种做法是十分灵活方便的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值