您的位置:首页 > Web前端 > JavaScript

JavaScript函数的两种主要调用模式以及原型方法等

2010-10-20 16:59 148 查看
1)方法调用模式

当一个函数作为method绑定到一个对象时,这个function如果作为属性被调用是方法调用模式。方法调用传递this为该对象,所以方法可以通过this来访问对象的属性或者变量。

2)函数调用模式

此时,this被绑定为全局变量。所以注意内部函数的情况,this并不是指的调用此函数的外部函数。

var myObj = {
value:0;
increment:function(inc){
this.value += typeof inc === 'number'?inc:1;
}
dobule:function(){
var that = this;
var helper = function(){
that.value = add(that.value,that.value);
}
helper();
}
};
// method invoke
myObj.increment();  //1
myObj.increment(2);//3
// method and Function invoke pattern
myObj.double();  //6


3)原型构造模式,apply调用模式:并不常用不再介绍。

4)JS允许给语言的基本类型增加方法,比如给Number类型增加一个提取整数部分的方法或者String增加trim空字符的函数,这里还写了一个原型方法来弥补float做除法时的bug

Function.prototype.method = function(name,func){
if(!this.prototype[name]){
this.prototype[name]=func;
}
return this;
};
Number.method('integer',function(){
return Math(this<0?'celling':'floor')(this);
});
String.Method('trim',function(){
return this.replace(/^/s+|/s+$/g,'');
});
document.write(-1/2.integer());


Number.prototype.division = function(val2){
var val1 =this;
while(parseInt(val1*=10)<1|parseInt(val2*=10)<1);
return parseInt(val1)/parseInt(val2);
}
var num = 0.00007;
alert(num.division(10));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: