[英]Javascript Object.create is not inheriting from the parent
我希望man對象從person對象繼承。 我可以使用new運算符完成此操作,但它應該與Object.create
。 但是為什么它不起作用? console.log
表示undefined
而不是預期的hello
。
function person() { this.say="hello"; } function man() { this.name="John Miler"; } man.prototype = Object.create(person); var Johnny = new man(); console.log(Johnny.say);
您的問題有兩個。
應該將Object.create
傳遞給prototype
,而不是構造函數。 在這種情況下,您應該使用Object.create(person.prototype);
,而不是Object.create(person);
在調用構造函數時會添加say
屬性,而您永遠不會從子構造函數中調用父構造函數。
有兩種方法可以解決此問題,具體取決於您的期望行為。
call
父構造函數。 person.call(this);
function person() { this.say="hello"; } function man() { person.call(this); this.name="John Miler"; } man.prototype = Object.create(person.prototype); var Johnny = new man(); console.log(Johnny.say);
person.prototype.say = "hello";
function person() { } person.prototype.say = "hello"; function man() { this.name="John Miler"; } man.prototype = Object.create(person.prototype); var Johnny = new man(); console.log(Johnny.say);
如果您要實現的目的是使man對象繼承person對象,請嘗試以下操作:
// superclass
function Person() {
this.say = "hello";
}
// superclass method
Person.prototype.doStuff = function() {
console.info('Stuff done.');
};
// subclass
function Man() {
Person.call(this); // call super constructor.
this.name="John Miler";
}
// subclass extends superclass
Man.prototype = Object.create(Person.prototype);
Man.prototype.constructor = Man;
var Johnny = new Man();
console.log(Johnny.say); // hello
Object.create應該傳遞給原型而不是構造函數。
function person() {
this.say="hello";
}
function man() {
this.name="John Miler";
}
man.prototype = Object.create(new person());
var Johnny = new man();
console.log(Johnny.say);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.