我希望 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);
最佳答案
你的问题有两个。
问题 1:
Object.create
应该传递 prototype
,而不是构造函数。在这种情况下,您应该使用 Object.create(person.prototype);
,而不是 Object.create(person);
问题 2:
say
属性是在调用构造函数时添加的,并且您永远不会从子构造函数调用父构造函数。
有几种方法可以解决这个问题,具体取决于您想要的行为。
选项 1,调用
父构造函数。
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);
关于Javascript Object.create 不是从父级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251361/