2017-01-15 1 views
2

I 두 버전 코드자바 스크립트 프로토 타입 Object.create

let Animal = function() 
    { 

    } 

    Animal.prototype.voice = "Miau" 


    let Cat = function() 
    { 

    } 
    Cat.prototype = Object.create(Animal.prototype); 

    let flippy = new Cat(); 

    console.log(flippy.voice) 

이 버전은 vorked와 "Miau"를 반환했지만 두 번째 버전

let Animal = function() 
{ 
    this.voice = "Miau" 
} 


let Cat = function() 
{ 

} 
Cat.prototype = Object.create(Animal.prototype); 

let flippy = new Cat(); 

console.log(flippy.voice) 

이 근무하지만 flippy.voice를 호출하지 못할 이유는 false를 반환? 어떻게 부르지? 음성?

답변

4

flippy.voice으로 전화를 걸 수없는 이유는 무엇입니까?

어떤 코드가 지금까지 실행 한하지 않았기 때문에 그것을 만든 것이라고, flippy에는 voice이 없기 때문에.

자바 스크립트에서 생성자를 유도 할 때, 하위의 생성자에서 슈퍼의 생성자를 호출하는 것이 중요합니다 :

let Cat = function() { 
    Animal.call(this); // <==== 
}; 

당신이 다음 Animal의 코드가 실행되는 않는 것이 있다면, 그리고 인스턴스는 voice 속성이됩니다 .

참고 : 또한 Cat.prototypeconstructor 특성을 수정하는 것이 유용하다 :

let Cat.prototype = Object.create(Animal.prototype); 
Cat.prototype.constructor = Cat; // <=== 

Animal 잘못 ... "Miau"voice 보인다 설정 가지는 말했다. 아마 이것을 논증으로 받아들이겠습니까? 2017 여기에 물론

let Animal = function(voice) { 
    this.voice = voice; 
}; 

let Cat = function() { 
    Animal.call(this, "Miau"); 
}; 

let Cat.prototype = Object.create(Animal.prototype); 
Cat.prototype.constructor = Cat; 

let flippy = new Cat(); 
console.log(flippy.voice); // "Miau" 

, 당신은 단순화하기 위해 class 구문 (필요한 경우 이전 대상 환경에 transpiling)를 사용할 수 있습니다 :

class Animal { 
    constructor(voice) { 
     this.voice = voice; 
    } 
} 

class Cat extends Animal { 
    constructor() { 
     super("Miau"); 
    } 
} 

let flippy = new Cat(); 
console.log(flippy.voice); // "Miau" 
+0

내 생각이 Object.create (기능을 확장합니다. 프로토 타입) 동일 물 –

+0

@ MurdSofiyev : 무엇과 같은 거죠? 'Cat'에서'Animal'을 호출하는 것과 같은 것은 아니며'constructor'을 올바른 값으로 설정하지 않습니다. –