简体   繁体   English

Javascript Object.create不是从父级继承

[英]Javascript Object.create is not inheriting from the parent

I want the man object inherits from the person object. 我希望man对象从person对象继承。 I could have done it using the new operator, but it should work with Object.create . 我可以使用new运算符完成此操作,但它应该与Object.create But why it is not working? 但是为什么它不起作用? The console.log says undefined instead of the expected hello . 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); 

Your problem is two-fold. 您的问题有两个。

Problem 1: 问题一:

Object.create should be passed the prototype , not the constructor. 应该将Object.create传递给prototype ,而不是构造函数。 In this case, you should use Object.create(person.prototype); 在这种情况下,您应该使用Object.create(person.prototype); , not Object.create(person); ,而不是Object.create(person);


Problem 2: 问题2:

The say property is added when the constructor is called, and you never call the parent constructor from the child constructor. 在调用构造函数时会添加say属性,而您永远不会从子构造函数中调用父构造函数。

There are a couple ways to solve this, depending on your desired behavior. 有两种方法可以解决此问题,具体取决于您的期望行为。

Option 1, call parent constructor. 选项1, call父构造函数。

person.call(this);

Sample: 样品:

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

Option 2, make it a static property. 选项2,使其成为静态属性。

person.prototype.say = "hello";

Sample: 样品:

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

If what you try to achieve is for a man object to inherit a person object, try this: 如果您要实现的目的是使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 should be passed the prototype not the constructor. 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