2017-05-22 1 views
1

필자는 Vehicle의 toString 메소드를 새로운 toString 메소드로 덮어 쓸 것으로 기대했다. 그러나 이것은 작동하지 않는 것 같아요. 왜 그런지 모르겠습니다. 이 문서를 바탕으로 그것이 https://strongloop.com/strongblog/an-introduction-to-javascript-es6-classes/Object.create의 두 번째 인수가 속성 설명뿐 아니라 값을 포함하도록되어 같은 속성이 지정된 객체두 번째 인자 Object.create

function Vehicle(make, year) { 
    this.make = make; 
    this.year = year; 
} 

Vehicle.prototype.toString = function() { 
    return this.make + ' ' + this.year; 
}; 

var vehicle = new Vehicle('Toyota Corolla', 2009); 

function Motorcycle(make, year) { 
    Vehicle.apply(this, [make, year]); 
} 

Motorcycle.prototype = Object.create(Vehicle.prototype, { 
    toString: function() { 
    return 'Motorcycle ' + this.make + ' ' + this.year; 
    } 
}); 

Motorcycle.prototype.constructor = Motorcycle; 

var motorcycle = new Motorcycle('harley', 2010); 
console.log(motorcycle.toString()); //TypeError 

답변

4

(확장 클래스 아래로 스크롤)해야처럼 보인다. 이렇게하면 문제가 해결됩니다.

Motorcycle.prototype = Object.create(Vehicle.prototype, { 
    toString: { 
    configurable: true, enumerable: true, writable: true, 
    value: function() { 
     return 'Motorcycle ' + this.make + ' ' + this.year; 
    } 
    } 
}); 

MDN reference for Object.create도 참조하십시오.

+0

감사합니다. 나는 가치 속성이 필요하다는 것을 깨닫지 못했다. 다른 속성 값을 변경할 필요가 없다는 것을 추가하기 만하면됩니다. 그들은 기본적으로 false로 초기화됩니다. – MattGoldwater

+0

실제로; 이들 모두에 대해 true는 귀하의 예제에서 'Vehicle.prototype.toString'과 같이 속성이 일반적으로 생성되는 방식과 간단히 일치합니다. –