簡體   English   中英

Javascript Object.create不是從父級繼承

[英]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);


問題2:

在調用構造函數時會添加say屬性,而您永遠不會從子構造函數中調用父構造函數。

有兩種方法可以解決此問題,具體取決於您的期望行為。

選項1, 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); 

選項2,使其成為靜態屬性。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM