js 函数调用方式
js 函数调用模式1.方法调用模式2.函数调用模式 3.构造器调用模式 4.Apply 调用模式在javascript中一共有四
js 函数调用模式
1.
方法调用模式
2.函数调用模式
3.构造器调用模式
4.Apply 调用模式在javascript中一共有四种调用模式:方法调用模式、函数调用模式、构造器调用模式和apply调用模式。这些模式在如何初始化关键参数this上存在差异
1.方法调用模式
当一个函数被保存为对象的一个属性时,我们称之它为该对象的一个方法,那么this被绑定到该对象上。
function MyObject(name){
this.name=name || 'MyObject';
this.value=0;
this.increment=function(num){
this.value += typeof(num) === 'number' ? num : 0;
};
this.toString=function(){
return '[Object:'+this.name+' {value:'+this.value+'}]';
}
this.target=this;
}
function getInfo(){
return this.toString();
}
var myObj=new MyObject();
alert(getInfo.apply(myObj));//[Object:MyObject {value:0}],this指向myObj
alert(getInfo.apply(window));//[object Window],this指向window