apply、call
call(),apply()
1、每个函数都包含两个非继承而来的方法:call()和apply()
2、在特定的作用域内调用函数,等于设置函数体内的this对象,以扩充函数赖以运行的作用域
3、apply()接受两个参数,一个是函数运行的作用域,另一个是参数数组。而call()是将参数一个个列出来
一般来说,this总是指向调用方法的对象,但是使用call()和apply()方法时,就会改变this指向
el:简单例子
window.firstName="window";
var myObject={firstName:"myobject"};
function myAction(word){
this.firstName="myAction";
this.GetMeassage=function(word){
if(typeof(word)=="string"){
console.log(this.firstName+"_"+word);
}else{
console.log(this.firstName);
}
}
}
var myaction=new myAction();
myaction.GetMeassage(); //myAction
myaction.GetMeassage.call(window); //window
myaction.GetMeassage.call(myObject); //myobject
myaction.GetMeassage.call(myObject,"未知"); //myobject_未知
myaction.GetMeassage.apply(window); //window
myaction.GetMeassage.apply(myObject); //myobject
myaction.GetMeassage.apply(myObject,["未知"]); //myobject_未知