7

この質問はUsing "Object.create" instead of "new"の重複ではありません。問題のスレッドは、使用時に引数を正しく渡すことに焦点を当てていませんObject.create


Object.createではなく を使用してオブジェクトを初期化する方法に興味がありますnew。これまでの私のコードは次のとおりです。

function Human(eyes) {
    this.eyes = eyes || false;
}

Human.prototype.hasEyes = function() {
    return this.eyes;
}

function Male(name) {
    this.name = name || "No name";
}

Male.prototype = new Human(true); //passing true to the Human constructor

var Sethen = new Male("Sethen");

console.log(Sethen.hasEyes());

上からわかるように、 はMale.prototype = new Human(true);true で新しいオブジェクトを作成します。hasEyes()関数が実行されると、期待どおりに true が記録されます 。

それで、私の質問は..パラメータObject.createを渡すのと同じ方法でこれを行うにはどうすればよいですかtrue??

4

2 に答える 2

8

を使用してコンストラクターを呼び出し、Object.call(this)引数を渡す必要があります。

function Human(eyes, phrase) {
    this.eyes = eyes || false;
    this.phrase = phrase;
}

Human.prototype.hasEyes = function() {
    return this.eyes;
}

Human.prototype.sayPhrase = function() {
    return this.phrase;
}

function Male(name) {
    Human.call(this, true, "Something to say"); //notice the call and the arguments
    this.name = name || "No name";
}

Male.prototype = Object.create(Human.prototype);

var Sethen = new Male("Sethen");

console.log(Sethen.hasEyes());
console.log(Sethen.sayPhrase());

console.log(Object.getOwnPropertyNames(Sethen));

これは機能し、オブジェクトMaleは と のプロパティを持ちeyesますphrase

于 2012-12-25T04:17:54.610 に答える