1

我不是非常好,Javascript继承aquainted,我试图使一个物体从另一个继承,并定义自己的方法Javascript继承覆盖第一个(FooB.prototype = new Foo() is cancelled out)。有什么办法可以解决这个问题,还是我的方向不对?从多个对象

在此先感谢,对于任何不好的术语感到抱歉。

回答

5

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

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

有没有办法用另一个对象扩展原型,而不覆盖它? – tcooc 2011-01-20 11:50:56

2

一个解决办法是:

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

FooB.prototype = p; 

更新:关于与现有对象扩大。您可以随时一个对象的现有属性复制到另一个问题:只要proto是一个“普通”对象

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

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

(即不从另一个对象继承),它是好的。否则,您可能需要添加if(proto.hasOwnProperty(prop))以仅添加非继承属性。

+0

`proto`可以是一个 “普通” 的对象,但如果第三方脚本增强`Object.prototype`你最终会复制这些值`FooB。 prototype`。 – galambalazs 2011-01-20 12:39:43

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; 
}