2012-07-17 2 views
2

저는 Pers에서 온 파생 된 (Perspective) 직원과 직원이 있습니다.프로토 타입을 사용할 때 JavaScript 객체를 덮어 씁니다.

Pers = function(options){ 
    this.Name; 
    this.ID; 
    this.init = function(options){ 
    this.Name=options.Name; 
    this.ID=options.ID; 
    } 
} 

Employee = function(options){ 
    this.Sal; 
    this.init = function(options){ 
    this.Sal=options.Sal; 
    this.__proto__.init(options); 
    } 
    this.init(options); 
} 

Employee.prototype=new Pers(); 

지금 나는 두 번 "타냐"을 얻을 것이다 ...

var o=new Employee({Name:"Nik",ID:"1",Sal:100}); 
var p=new Employee({Name:"Tanja",ID:"2",Sal:200}); 

새로운 개체를 만들고 자신의 이름을 알릴 때.

누구에게 아이디어가 있습니까?

+3

더 이상 '__proto__'을 사용하면 안됩니다. –

답변

3
this.__proto__.init(options); 

당신이 프로토 타입을 수정하는 원인이 this로 프로토 타입 자체 프로토 타입에 init 메소드를 호출합니다. 당신이 그것을 그림자 전에 프로토 타입 init 함수에 대한 참조를 저장할 수 있습니다

__proto__을 방지하기 위해 편집

this.__proto__.init.apply(this, [options]); 

보십시오 : 당신은 잘못된 범위에 init를 호출하고

Employee = function(options){ 
    this.Sal; 
    var protoInit = this.init; 
    this.init = function(options){ 
    this.Sal=options.Sal; 
    protoInit.apply(this, [options]); 
    } 
    this.init(options); 
} 
+3

'Object.create'에 대해서'call (this, options)'가 아마 – OrangeDog

2

. 이런 식으로 해보십시오.

function Person(opt) { 
    this.name = opt.name; 
    this.id = opt.id; 
} 

function Employee(opt) { 
    Person.call(this, opt); 
    this.sal = opt.sal; 
} 

Employee.prototype = Object.create(Person.prototype, {}); 

이제 Person.prototypeEmployee.prototype의 속성을 설정할 수 있습니다 예상대로 그들은 행동해야한다.

이렇게하면 해킹 된 더 이상 사용되지 않는 속성 (__proto__)을 사용하지 않아도되고 훨씬 더 명확 해집니다. Object.create은 수퍼 생성자를 실제로 호출하지 않고 슈퍼 생성자의 프로토 타입을 사용하여 인스턴스를 만드는 데 사용됩니다 (init 호출의 필요성 제거). 많은 라이브러리의 inherits 구현이 수행하는 것처럼 반 표준 속성 정의 (예 : superconstructor)를 포함 할 수 있습니다.

+0

+1이 더 낫습니다. –

+0

새 개체를 만들 때이 작업이 작동하지 않습니다. var o = new Employee ({name : "Nik", id : "1", sal : 100}); var p = new Employee ({name : "Tanja", id : "2", sal : 200}); o.name을 찾을 수 없습니다. 내가 뭘 잘못하고 있니? –

+0

'init'없이 다시 쓰는 서둘러서, 나는 당신이했던 것과 같은 실수를 저질렀습니다. 답변이 수정되었습니다. – OrangeDog

관련 문제