call和apply:数组
每一个函数都包含两个非继承来的方法:call方法和apply方法,这两个方法的做用是同样的。app
都是在特定的做用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的做用域。通常来讲,this总会指向调用某个方法的对象,可是使用call和apply方法时候,就会改变this的指向。函数
call方法使用实例:this
例子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);//blueblog
例子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,结果是Speakwangthree
apply方法使用实例:作用域
例子1:io
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