기본 개체에서 인스턴스 속성을 상속하거나 복사하는 일련의 개체를 만들고 싶습니다. 이로 인해 어떤 패턴을 사용해야하는지에 대한 결정을 내릴 수 있었고 어떤 방법이 "더 나은가"에 대한 의견을 묻기를 원했습니다. 둘 다 공통 템플릿을 기반으로 같은 일, 즉 고유 한 인스턴스 속성을 달성복제 또는 적용 : "더 나은"것인가?
는//APPLY:
// ---------------------------------------------------------
//base object template
var base = function(){
this.x = { foo: 'bar'};
this.do = function(){return this.x;}
}
//instance constructor
var instConstructor = function (a,b,c){
base.apply(this);//coerces context on base
this.aa = a;
this.bb = b;
this.cc = c;
}
instConstructor.prototype = new base();
var inst = function(a,b,c){
return new instConstructor(a,b,c);
}
//CLONE
// ---------------------------------------------------------
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var x = {foo: 'bar'};
function instC(a,b,c){
this.aa = a;
this.bb = b;
this.cc = c;
this.x = clone(x);
};
instC.prototype.do = function(){
return this.x;
}
- 질문은 당신이 찾고있는 같은 질문의 소리
'inst.prototype = ...'을 설정하는 것은 정말로 효과가 있습니까? 당신은'inst'를 다음 줄의 함수와 똑같이 할당 했습니까? 그것은'instConstructor.prototype = ... '이되어야합니다. – nnnnnn
좋은 점 - 죄송합니다. - 오타였습니다. – sunwukung