Frage

Ich habe vor kurzem mit Prototyping in Javascript zu experimentieren, und ich kann nicht herausfinden, warum der folgende Code funktioniert nicht. Was würde Ich mag es tun, um eine neue Instanz von Käse mit dem Parameter n erstellen.

function food(n) {
    this.n=n;
}
function cheese(n) {
    alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');
War es hilfreich?

Lösung

Sie erstellen eine neue Cheese Instanz, und das Argument n an dem Cheese Instanzvariable this.n nie verwendet oder zugeordnet, da diese Logik nur auf dem Food Konstruktor verwendet wird.

Sie können ein paar Dinge tun:

1. Nehmen der Food Konstruktor in der Cheese Funktion, die arguments mit Objekt und der neu geschaffene Kontext (this).

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

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

new Cheese('paramesian');

2. Wiederholen Sie die Food Konstruktor Logik (this.n = n) auf der Cheese Konstruktorfunktion:

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

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

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

3. Verwenden Sie eine andere Technik, wie Macht Bauer :

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. Eine weitere Option, prototypal Vererbung :

// 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'

Andere Tipps

Scheint, wie Sie wollen einfach nur wissen, wie Prototyp funktioniert in JavaScript verketten. Im Folgenden ist eine ausgezeichnete, einfach und gut erklärt Tutorial http://www.herongyang.com/JavaScript/Inheritance- von-Constructor-Prototype-Object.html

Bearbeiten : Das ist offenbar nicht prototypische Vererbung (siehe Kommentare), aber es scheint für diesen besonderen Zweck zu arbeiten.

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

    alert(this.n);
}

new cheese('paramesian');
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top