7

这个问题不是重复使用 "Object.create" 而不是 "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);创建了一个新的对象。运行该hasEyes()函数时,这将按预期记录为真。

所以,我的问题是.. 使用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具有eyesphrase

于 2012-12-25T04:17:54.610 回答
0

这是否为原型继承模型提供了一些线索。

const Human = {
    constructor: function (eyes) {
        this.eyes = eyes || false;
    },
    hasEyes: function () {
        return this.eyes;
    }
};

let Male = Object.create(Human);

Male.constructor = function (name) {
    this.name = name || "No name";
    return Human.constructor.call(this, "true");
};

let Sethen = Object.create(Male);
Sethen.constructor = function() {
    return Male.constructor.call(this, 'Sethen');
};

Sethen.constructor();

console.log(Sethen.hasEyes());
console.log(Object.getOwnPropertyNames(Sethen));
于 2017-05-12T18:05:58.790 回答