문제

최근에 JavaScript에서 프로토 타이핑을 실험 해 왔으며 다음 코드가 작동하지 않는 이유를 알 수 없습니다. 내가하고 싶은 것은 매개 변수 n이있는 새로운 치즈 인스턴스를 만드는 것입니다.

function food(n) {
    this.n=n;
}
function cheese(n) {
    alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');
도움이 되었습니까?

해결책

당신은 새로운 것을 창조하고 있습니다 Cheese 인스턴스 및 논증 n 사용하거나 할당되지 않습니다 Cheese 인스턴스 변수 this.n, 그 논리는에만 사용되기 때문입니다 Food 건설자.

몇 가지 작업을 수행 할 수 있습니다.

1 . 적용하다 그만큼 Food 내부의 생성자 Cheese 기능을 사용합니다 arguments 개체와 새로 생성 된 컨텍스트 (this).

function Food(n) {
    this.n=n;
}

function Cheese(n) {
    Food.apply (this, arguments);
    alert(this.n);
}

new Cheese('paramesian');

2. 반복하십시오 Food 생성자 로직 (this.n = n)에 Cheese 생성자 기능 :

function Food(n) {
    this.n=n;
}

function Cheese(n) {
    this.n = n;
    alert(this.n);
}

Cheese.prototype = new Food();
new Cheese('paramesian');

삼 . 다른 기술을 사용하십시오 전력 생성자:

function food (n) {
  var instance = {};
  instance.n = n;

  return instance;
}


function cheese (n) {
  var instance = food(n);
  alert(instance.n);

  return instance;
}

cheese('parmesian');
cheese('gouda');

4. 또 다른 옵션, 프로토 타입 상속:

// helper function
if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    function F () {}
    F.prototype = o;
    return new F();
  };
}

var food = {
  n: "base food",
  showName : function () { alert(this.n); }
};

var cheese1 = Object.create(food);
cheese1.n = 'parmesian';
cheese1.showName(); // method exists only in 'food'

다른 팁

프로토 타입 체인이 JavaScript에서 어떻게 작동하는지 이해하고 싶은 것 같습니다. 다음은 훌륭하고 간단하며 잘 설명 된 튜토리얼입니다.http://www.herongyang.com/javaScript/inheritance-from-constructor-prototype-object.html

편집하다, 이것은 분명히 프로토 타입 상속이 아니지만 (주석 참조),이 특별한 목적에 효과가있는 것 같습니다.

function food(n) {
    this.n=n;
}
function cheese(n) {
    this.prototype = food;
    this.prototype(n);

    alert(this.n);
}

new cheese('paramesian');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top