[英]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. 您的问题有两个。
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);
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. 有两种方法可以解决此问题,具体取决于您的期望行为。
call
parent constructor. 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);
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.