我们从下面给出的方法得到相同的结果。但是哪种方式更有效,哪种方式占用的内存更少。
function a(){
this.addclass= function(){
//do something
}
}
function a(){}
a.prototype.addclass= function(){
//do something
}
答案 0 :(得分:1)
我认为,考虑到继承的情况,你建议的两种方式都有不同的行为,这在下面的代码部分是显而易见的:
通过addclass
prototype
方法
function a() {
a.prototype.addclass= function() {
alert('a');
};
}
a();
function b() {}
b.prototype = Object.create(a);
var o = new b();
o.prototype.addclass();
使用addclass
this
方法
function a() {
this.addclass= function(){
alert('a');
};
}
a();
function b() {}
b.prototype = Object.create(a);
var o = new b();
o.prototype.addclass();
通过原型(第一个)可以访问其父级的addclass
方法,而通过此方式(第二个),addclass
的访问权限特定于' a&#39 ;功能。