当前位置:Gxlcms > JavaScript > JavaScript中的类添加通用方法

JavaScript中的类添加通用方法

时间:2021-07-01 10:21:17 帮助过:8人阅读

首先说明一点,JavaScript 不支持函数的重载,如果右多个函数名相同,它自己会调用距离他最近的那个,也就是最

后的那个函数,这个JS不支持函数重载的现象的东西需要特别的注意。

直接定义一个函数或者变量,他们是属于全局函数或者全局变量,本质上他们是属于window对象的。

然后还有对于JS中内置的对象,我们可以为他们提供一个通用的方法,这样就不需要专门写了。

代码如下

[javascript]
//我们可以给类添加方法
var i = new Number(10);
Number.prototype.add=function(a){
return this+a;
}

window.alert(i.add(20).add(30));
//我们可以给类添加方法
var i = new Number(10);
Number.prototype.add=function(a){
return this+a;
}

window.alert(i.add(20).add(30));
这样的话,我们就可以给Number这个对象的增加方法,我们就可以直接使用了。

再看一个代码

[javascript]
Array.prototype.find=function(val){
for(var i = 0; i < this.length; i++){
if(this[i] == val){
window.alert("下标为 "+i);
return;
}
}
window.alert("没有");
}

var t = new Array(3);
t[0] = 3;
t[1] = 5;
t[2] = 6;

t.find(4);
t.find(5);
Array.prototype.find=function(val){
for(var i = 0; i < this.length; i++){
if(this[i] == val){
window.alert("下标为 "+i);
return;
}
}
window.alert("没有");
}

var t = new Array(3);
t[0] = 3;
t[1] = 5;
t[2] = 6;

t.find(4);
t.find(5);
这样的话为Array对象提供了通用的方法,套用了this关键字,这样的prototype可以为相当于类的东西提供方法,Mark一下

人气教程排行