1

我不太熟悉javascript继承,我试图让一个对象从另一个对象继承,并定义它自己的方法:

function Foo() {}
Foo.prototype = {
    getColor: function () {return this.color;},
};
function FooB() {}
FooB.prototype = new Foo();
FooB.prototype = {
    /* other methods here */
};

var x = new FooB().getColor();

但是,第二个会覆盖第一个(FooB.prototype = new Foo() is cancelled out)。有什么办法可以解决这个问题,还是我走错了方向?

在此先感谢,对于任何不好的术语,我们深表歉意。

4

3 回答 3

6

每个对象只能有一个原型,所以如果你想在继承(复制)它之后添加到原型中,你必须扩展它而不是分配一个新的原型。例子:

function Foo() {}

Foo.prototype = {
    x: function(){ alert('x'); },
    y: function(){ alert('y'); }
};

function Foo2() {}

Foo2.prototype = new Foo();
Foo2.prototype.z = function() { alert('z'); };

var a = new Foo();
a.x();
a.y();
var b = new Foo2();
b.x();
b.y();
b.z();
于 2011-01-20T11:29:17.060 回答
2

一种解决方案是:

function FooB() {}
var p = new Foo();
p.methodA = function(){...}
p.methodB = function(){...}
p.methodC = function(){...}
...

FooB.prototype = p;

更新:关于使用现有对象进行扩展。您始终可以将一个对象的现有属性复制到另一个对象:

FooB.prototype = new Foo();
var proto = {
     /*...*/
};

for(var prop in proto) {
    FooB.prototype[prop] = proto[prop];
}

只要proto是“普通”对象(即不从另一个对象继承)就可以了。否则,您可能只想if(proto.hasOwnProperty(prop))添加非继承属性。

于 2011-01-20T11:24:56.677 回答
2

您可以使用extend将新成员复制到原型对象的函数。

function FooB() {}
FooB.prototype = new FooA();

extend(FooB.prototype, {
    /* other methods here */
});

延长

/**
 * Copies members from an object to another object.
 * @param {Object} target the object to be copied onto
 * @param {Object} source the object to copy from
 * @param {Boolean} deep  whether the copy is deep or shallow
 */
function extend(target, source, deep) {
    for (var i in source) {
        if (deep || Object.hasOwnProperty.call(source, i)) {
            target[i] = source[i];
        }
    }
    return target;
}
于 2011-01-20T12:33:36.000 回答