Javascript Object.create 不是从父级继承的
Javascript Object.create is not inheriting from the parent
我希望 man 对象继承自 person 对象。我本可以使用新运算符来完成,但它应该适用于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);
你的问题是双重的。
问题1:
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);
相关文章:
- 使用Object.create()的角度服务继承
- 使用Object.create作为原型的原型继承将[Object]作为实例的原型
- 使用 Object.create 进行继承
- 为什么 Object.create 在 JavaScript 中的原型继承方面没有做我所期望的
- Javascript Object.create 不是从父级继承的
- 为什么 Object 对象中的某些属性不会在子对象中继承
- ECMAScript 5定义了用于构造和继承的通用工厂模式[Object.create()]
- 原型继承和Object.create
- 使用Object.keys获取用于创建构造函数实例的属性,然后打印继承的属性
- Object.create与新继承混淆
- 使用Object.assign和Object.create进行继承
- 将' this '的继承扩展到' object '的方法/属性
- 在javascript“object”中继承属性
- for-in vs Object.没有继承属性的keys forEach
- 是否可以确定使用object创建的对象.create继承了JavaScript中的Array
- Object.create(BaseObject)和util的区别是什么?继承(MyObject BaseObject)
- 没有new或Object.create的原型继承
- 在JavaScript中继承Object的属性
- ie9中的Javascript对象列表无法继承Object.prototype
- JavaScript继承Object.create()未按预期工作