此问题与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
参数相同的方式进行此操作?
答案 0 :(得分: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));
这是有效的,现在对象Male
的属性为eyes
和phrase
答案 1 :(得分: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));