这取决于您真正想要达到的目标。
var Widget = function(){
this.name = 'Widget';
this.a = 'a';
};
Widget.prototype.foo = function(){ return 'foo'; };
var WidgetPlus = function(){
this.name = 'WidgetPlus';
this.b = 'b';
};
WidgetPlus.prototype = new Widget(); // XXX: assumption
WidgetPlus.prototype.bar = function(){ return 'bar'; };
// Ignores prototype chain
var copy = function(dest, src){
Object.keys(src).forEach(function(key){
dest[key] = src[key];
});
};
用 WidgetPlus.prototype 东西覆盖 widget_1 东西:
var widget_1 = new Widget();
copy(widget_1, WidgetPlus.prototype);
widget_1; // Widget {name: "Widget", a: "a", bar: function, foo: function}
加上复制初始化:
copy(widget_1, new WidgetPlus());
widget_1; // Widget {name: "WidgetPlus", a: "a", bar: function, b: "b", foo: function}
或者用 widget_1 东西覆盖新的 WidgetPlus() 东西
var widget_1 = new Widget();
var old_widget_1 = widget_1;
widget_1 = new WidgetPlus();
copy(widget_1, old_widget_1);
widget_1; // WidgetPlus {name: "Widget", b: "b", a: "a", bar: function, foo: function}
或许 WidgetPlus 并没有真正共享原型链
和Widget,它们的功能完全不同;和
你也想要那些:
copy(widget_1, Widget.prototype);
等等