使用Object.create而不是new时传递参数

Set*_*hen 5 javascript object-create

这个问题与使用"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());
Run Code Online (Sandbox Code Playgroud)

如上所示,Male.prototype = new Human(true);使用true创建一个新对象.hasEyes()运行该函数时,会按预期记录true.

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

Set*_*hen 6

您必须使用构造函数调用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));
Run Code Online (Sandbox Code Playgroud)

这个工程现在的对象Male具有的属性eyesphrase

  • 谢谢终于找到了一个在JavaScript中正确继承的帖子:) (2认同)