2017-11-25 22 views
1
내가 궁금

나는 garfield이 경우 Cat에 구성되어있는 개체의 속성에 액세스하려고 할 때 왜이 코드 조각에서, 나는 undefined을 얻고있다 :JS - 객체와 프로토 타입 상속 생성 기능

function Cat(){ 
    this.legs = 2; 
    this.species = 'cat'; 
}; 

Cat.prototype.makeSound = function() { 
    console.log(this.sound); // logs undefined 
}; 

const garfield = Object.create(Cat); 
garfield.sound = 'feed me'; 
garfield.makeSound(); 
console.log(garfield.legs) // logs undefined 

프로토 타입 상속 체인에서 해당 속성에 액세스 할 수 없습니까?

답변

3

단어 OOP은 정의에 "object"를 포함하고 있습니다. 당신이 물건을 다루고 있다는 것을 의미합니다.

자바 스크립트는 객체를 직접 노출하기 때문에 클래스를 사용하지 않고 추상화없이 사용할 수 있습니다.

개체를 만들려면 {}으로 선언하면됩니다. 예를 들어 java과 같은 클래스를 생성 할 필요가 없습니다.

상속을 직접 사용하려면 객체가 있어야하며 프로토 타입에 물건을 추가해야합니다. 여기

은 예입니다

const Cat = { 
 
    legs: 2, 
 
    species: 'cat', 
 
}; 
 

 
Object.setPrototypeOf(Cat, { 
 
    makeSound() { 
 
    console.log(this.sound); // logs undefined 
 
    } 
 
}) 
 

 

 
const garfield = Object.create(Cat); 
 
garfield.sound = 'feed me'; 
 
garfield.makeSound(); 
 
console.log(garfield.legs) //2

함수합니다 (this)에서 객체를 얻기 위해, 먼저 함수를 구성해야 할 것 함수를 사용하여 상속을 사용하고, 프로토 타입은 자동으로 this 개체에 추가됩니다. 귀하의 예를 Object.create에서

function Cat(){ 
 
    this.legs = 2; 
 
    this.species = 'cat'; 
 
}; 
 

 
Cat.prototype.makeSound = function() { 
 
    console.log(this.sound); // logs undefined 
 
}; 
 

 
const garfield = new Cat(); 
 
garfield.sound = 'feed me'; 
 
garfield.makeSound(); 
 
console.log(garfield.legs) // 2

+0

을 만들 Object.create를 사용할 수 있습니다, 단지'넣어 makeSound'를'Cat' 객체에 추가합니다. – Bergi

2

하지 클래스의 새 인스턴스를 만들한다! 함수를 만듭니다 (Cat은 함수이므로 함수의 프로토 타입을 전달합니다)!

사용 new이 새로운 인스턴스를 만들 수 있습니다

const garfield = new Cat(); 
console.log(garfield.legs); 

또는

function GarfieldLikeCat() {} 
GarfieldLikeCat.prototype = Object.create(Cat.prototype); 
GarfieldLikeCat.prototype.constructor = GarfieldLikeCat; 

고전 상속 얻을 수 있습니다 (이 아닌 새로운 인스턴스를!).

당신이 this.legs = 2;를 사용하지 않은 경우, 대신 Cat.prototype.legs = 2;, 당신은 내가 Object.setPrototypeOf` 여기에`사용하는 이유가 표시되지 않는 새로운 인스턴스를

function Cat() {} 
Cat.prototype.legs = 2; 
const garfield = Object.create(Cat.prototype); 
console.log(garfield.legs); 
+0

+1. 생성자 함수를 호출하지 않으면 객체를 생성하지 않을 것입니다 (즉,'legs'와'species'는 garfield에 추가되지 않습니다). 그래서'new'를 사용하거나 객체를 직접 사용하거나, 또는 공장 기능을 생성 할 수 있습니다. – Bamieh