//name:新增加方法的名字
//func:新增加的方法
Function.prototype.method = function(name,func){
this.prototype[name] = func;
return this;
}
function ClassA(name){
this.name = name;
}
function getName(){
return this.name;
}
function getPassword(){
return this.password;
}
function ClassB(name,password){
this.name = name;
this.password = password;
}
ClassB.prototype.getPassword = function(){
return this.password;
}
ClassA.method("getName",getName);
ClassA.method("getPassword",getPassword);
var a = new ClassA('xiaobai');
alert(a.getName());
ClassB.method("getName",getName);
ClassB.method("getPassword",getPassword);
var b = new ClassB('Ryan','123');
alert(b.getName());
alert(b.getPassword());
本文介绍了一种在JavaScript中为自定义类动态添加方法的技术。通过扩展Function.prototype,可以为ClassA和ClassB等类轻松增加如getName和getPassword等功能,无需修改原有类的定义。
104

被折叠的 条评论
为什么被折叠?



