我正在尝试使用javascript进行继承。首先,在网络上我发现了这个
function A() {}
function B(){}
B.prototype = new A() ;
B.prototype.constructor = B ;
这有效,但是当我使用B的prototype属性时,它不再起作用(http://jsfiddle.net/jeanluca/eQBUx/)
function A() {}
A.prototype.bar = function(){ return 'A'; }
function B() {}
B.prototype.bar = function(){ return 'B'; }
我知道你可以做
function B(){ this.bar = function(){ ... } } ;
但是我认为这绝对比使用原型定义它慢。那么在第二种情况下我该如何继承呢?
n
这是您的代码:
function A() {}
A.prototype.bar = function(){ return 'A';}
function B() {}
B.prototype.bar = function(){ return 'B'; }
B.prototype = new A() ; // replaces B's "bar" with A's "bar
var b = new B ;
console.log(b.bar());
如您所见,问题出在第六行。你第一次设定B.prototype.bar
的功能在第5行,然后你立刻设置B.prototype
到new A
第6行(有效地撤销你在5号线做了什么)。解决方案是将第6行放在第5行之前:
function A() {}
A.prototype.bar = function(){ return 'A';}
function B() {}
B.prototype = new A() ; // now it will work
B.prototype.bar = function(){ return 'B'; }
var b = new B ;
console.log(b.bar());
亲自观看演示:http : //jsfiddle.net/eQBUx/1/
另外,我也同意Bergi的建议:停止使用new
关键字。
更新:阅读您的评论并更详细地了解了您的问题之后,我建议您使用我的augment
库进行继承:
var A = Object.augment(function () {
this.constructor = function () {};
this.bar = function () {
return "A";
};
});
var B = A.augment(function (base) {
this.constructor = function () {};
this.bar = function () {
return "B" + base.bar.call(this);
};
});
var b = new B;
console.log(b.bar());
观看演示:http : //jsfiddle.net/eQBUx/2/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句