Javascript Object.create 不是从父级继承的

Javascript Object.create is not inheriting from the parent

本文关键字:继承 Object create Javascript      更新时间:2023-09-26

我希望 man 对象继承自 person 对象。我本可以使用新运算符来完成,但它应该适用于Object.create.但是为什么它不起作用?console.logundefined而不是预期的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);