js中的call方法和apply方法总结

call和apply:

每个函数都包含两个非继承来的方法:call方法和apply方法,这两个方法的作用是一样的。

都是在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。一般来说,this总会指向调用某个方法的对象,但是使用call和apply方法时候,就会改变this的指向。

call方法使用实例:

例子1:

window.color="red";
document.color='yellow';
var s1 = {color:'blue'};
function changeColor(){
console.log(this.color);
}
changeColor.call();//red
changeColor.call(window);//red
changeColor.call(document);//yellow
changeColor.call(this);//red
changeColor.call(s1);//blue

例子2:

var pet={
words:'....',
speak:function(say){
console.log(say+''+this.words)
}
}
pet.Speak('speak');
var Dog = {
words:'wang'
}
Pet.speak.call(Dog,'Speak')//将this的指向改成了Dog,结果是Speakwang

apply方法使用实例:

例子1:

window.number = 'one';
document.number='two';
var s1={number:'three'};
function changeColor(){
console.log(this.number);
}
changeColor.apply();//one
changeColor.apply(window);//one
changeColor.apply(document);//two
changeColor.apply(this);//one
changeColor.apply(s1);//three

同:

window.number = 'one';
document.number='two';
var s1={number:'three'};
function changeColor(){
console.log(this)
return this.number;
}
console.log(changeColor());//one
console.log(changeColor(window));//one
console.log(changeColor(document));//two
console.log(changeColor(this));//one
console.log(changeColor(s1));//three

这两个的区别是改变了this的指向。函数里面用了return的话,则在调用的时候就需要把他执行出来,并没有打印出来。但是上例子是可以打印的,因为函数里面有了打印的消息。

例子2:

function pet(words){
this.words = words;
this.speak = function(){
console.log(this.words)
}
}
function Dog(words){
pet.call(this,words)//wang
pet.apply(this,arguments)//wang
}
var dog = new Dog('wang')
dog.speak();

3.不同点:接收参数的方式的不同

apply的方法接收两个参数,一个是函数运行的作用域(this),另一个是参数数组

语法:apply([thisobj [,argArray]]);调用一个对象的一个方法,另个对象替换当前对象。

说明:如果argArray不是一个有效数组或不是arguments对象,那样将导致一个typeError,如果没有提供argArray和thisObj任何一个参数,那个Global对象将用作thisObJ.

call方法。第一个参数和apply()方法的一样,但是传递给函数的参数必须列举出来。

语法:call([thisObject[,arg1 [,arg2 [,...,argn]]]]);应用g某一对象的一个方法,用另一个对象替换当前对象。

call方法可以用来代替另一个对象调用方法,call方法可以将一个函数的对象上下文从初始的上下文改变为thisObject制定的新对象。如果没有提供thisObject参数,那个Global对象呗用于thisObject

原文地址:https://www.cnblogs.com/zwjx/p/9686228.html