재정의 된 경우 프로토 타입 메서드에서 일반 메서드를 호출 할 수 있습니까? 주어진 예제에서 첫 번째 eat () 메서드는 Animal 함수의 본문에서 호출됩니다. 이것이 요구 사항입니다.
Animal = function(){
this.eat();
};
Animal.prototype.eat = function() {
console.log("All animals eat");
};
Bear = function(){
Animal.call(this);
this.goToSleep = function(){
console.log("Bears go to sleep after they eat");
}
};
Bear.prototype = Object.create(Animal.prototype);
Bear.prototype.eat = function() {
console.log("Bears eat honey");
this.goToSleep(); //returns 'undefined is not a function'
//How do I invoke this.goToSleep() ?
};
var winnie = new Bear();
문제는 곰이 처음 호출 goToSleep
될 때 메서드 가 없다는 것 eat
입니다.
당신이 호출 할 때 Animal.call(this)
당신의 Bear
생성자는 다음 호출 eat
-에서 발견되는 Bear.prototype
및 호출. 그런 다음 eat
호출을 시도 goToSleep
하지만 goToSleep
아직 추가하지 않은 인스턴스 메서드입니다 ( 아직 Animal.call
도달 this.goToSleep = function()
하지 않은 상태 임을 기억하십시오 ).
타당한 이유가 없다면 다음 goToSleep
과 같이 프로토 타입 메서드가되어야합니다 eat
.
Bear.prototype.goToSleep = function(){
console.log("Bears go to sleep after they eat");
};
이것은 당신이 원하는대로 작동 합니다.
경우 또는 goToSleep
이 (당신이 당신의 생성자에서 만든 일부 민간 상태에 액세스해야하기 때문에) 인스턴스 방법으로, 단순히 당신의 순서 전환 Animal.call
및 this.goToSleep
라인 :
this.goToSleep = function() // etc.
Animal.call(this);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다