. WidgetPlus.prototype 물건과
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];
});
};
덮어 쓰기 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}
아니면 어쩌면 위젯 플러스는 프로토 타입 체인 을 위젯과 공유하지 않으며 완전히 다른 기능을 가지고 있습니다. 그리고 당신은 그 역시 원하는 :
copy(widget_1, Widget.prototype);
등 이러한 개체의
방금 변경 안 프로토 타입? 'widget_1.prototype = WidgetPlus'와 비슷합니다. – justanothercoder
@justanothercoder : 아니요, 작동하지 않습니다. – Bergi
왜 첫 번째 경우에'new WidgetPlus'를 사용하지 않았습니까? 당신이 필요로하는 것을 어떻게 결정합니까? 언제 변화합니까? 두 유형의 차이점은 무엇입니까? 'WidgetPlus'는'Widget'의 하위 클래스입니까? – Bergi