在使用Object时传递参数.创建而不是新建

Passing arguments when using Object.create as opposed to new

本文关键字:创建 新建 参数 Object      更新时间:2023-09-26

这个问题不是Using "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);用true创建了一个新对象。当hasEyes()函数运行时,它将按照预期记录为true。

所以,我的问题是……使用Object.create我将如何去做同样的方式传递true参数??

必须使用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的属性

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

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));