Sie erstellen eine neue Cheese
Instanz, und das Argument n
nie verwendet wird oder das auf den Cheese
Instanzvariable this.n
, da diese Logik nur auf dem Food
Konstruktor verwendet wird.
Sie können ein paar Dinge tun:
1. Apply Der Food
Konstruktor innerhalb der Cheese
Funktion, mit dem arguments
Objekt und dem neu erstellten 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 power constructors:
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 inheritance:
// 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'
Ich mag # 3, aber Sie müssen das "neue" vor "Essen (n)" entfernen. – Magnar
@Magnar, ja war ein Tippfehler, behoben, keine "diese" oder "neue" verwendet ... – CMS
Danke für die informative Antwort. Option Nummer 1 scheint für jetzt die beste Wahl zu sein, zumindest bis man # 3 vollständig versteht. – Kenneth