使用prototype属性的javascript继承

javascript inheritance using the prototype property

本文关键字:javascript 继承 属性 prototype 使用      更新时间:2023-09-26

我正在尝试用javascript进行继承。首先,在网上我发现了这个

function A() {}
function B(){}
B.prototype = new A() ;
B.prototype.constructor = B ;

这是有效的,但是当我使用B的原型属性时,它就不再有效了(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(){ ... } } ;

但我认为这肯定比使用原型来定义它要慢。那么,在第二种情况下,我该如何继承呢?

Thnx

这是您的代码:

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());

正如你所看到的,问题出在你的第六行。您首先在第5行将B.prototype.bar设置为函数,然后在第6行立即将B.prototype设置为new A(实际上撤消了您在第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/

使用this分配属性会破坏原型链。它的效率非常低,而且你不能用它来获得继承。所以不是吗?

您正在原型对象上创建一个属性,然后将其完全替换。反之亦然,在对象上创建bar方法。不要使用new

function B() {}
// first create the prototype object
B.prototype = Object.create(A.prototype);
// then assign properties on it
B.prototype.bar = function(){ return 'B'; }