javascript继承使用prototype属性

时间:2013-08-05 11:37:22

标签: javascript inheritance prototype

我正在尝试在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(){ ... } } ;

但我认为这肯定比使用原型定义它要慢。那么我怎么能在第二种情况下做继承?

日Thnx

3 个答案:

答案 0 :(得分:2)

使用this分配属性会破坏原型链。这是非常低效的,你不能用它来获得继承。那么......不是吗?

答案 1 :(得分:2)

您正在原型对象上创建一个属性,之后您将完全替换它。反之亦然,在 new 对象上创建bar方法。并don't use 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'; }

答案 2 :(得分:2)

这是你的代码:

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

正如您所看到的那样,问题出在第6行。您首先将B.prototype.bar设置为第5行中的某个功能,然后立即在第6行中将B.prototype设置为new A(有效撤消您在第5行中所做的操作)。解决方案是在第5行之前放置第6行:

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:Stop using the new keyword


更新:在阅读您的评论并更详细地了解您的问题后,我建议您使用我的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/