首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js 函数调用方式

2012-11-26 
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

热点排行
Bad Request.