假设我有 5 个对象
Callback
Perishable
Object1
Object2
Object3
Object1 需要扩展 Callback 而不是 Perishable 对象,而 Object 2 应该扩展两者,而 Object 3 应该扩展 Perishable 但不是 callback。
我知道这行得通...
Object1.prototype = new Callback();
Object3.prototype = new Perishable();
但是我该怎么做(我知道这行不通)
Object2.prototype = new Callback() && new Perishable();
最佳答案
如果你不需要任何外部依赖,你可以使用extend
的这个实现:
function __extends(d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
var a = function(){}; a.prototype = new b();
for (var p in a.prototype) d.prototype[p] = a.prototype[p];
};
例子:
var animal = function(){
};
animal.prototype.run = function(){
console.log("running");
};
var feline = function(){
};
feline.prototype.hunt = function(){
console.log("hunting");
};
var cat = function(){
};
__extends(cat, animal);
__extends(cat, feline);
var scaryCat = new cat();
scaryCat.run();
scaryCat.hunt();
fiddle :http://jsfiddle.net/apqwf93a/9/
关于具有多个对象的 Javascript 原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784204/