首页 > 解决方案 > Object.Create 带有原型的调用函数

问题描述

好的,我有这个工作:

const personProto2 = {
  calAge() {
    console.log(2021 - this.birthday);
  },
};
const rein = Object.create(personProto2);
rein.name = "Rein";
rein.birthday = 1945;
rein.calAge();

但如果我这样做:

const Person = function (name, birthday) {
  this.name = name;
  this.birthday = birthday;
};

Person.prototype.calAge = function () {
  console.log(2021 - this.birthday);
};
const rein = Object.create(Person);
rein.name = "Rein";
rein.birthday = 1945;
rein.prototype.calAge();

它不起作用。但函数也是对象。一个对象也有一个原型。

那么为什么第二个例子不起作用呢?

标签: javascript

解决方案


我认为您的意思是new在创建空白的纯 JavaScript 对象时使用。

new运算符允许您创建用户定义的对象类型或具有构造函数的内置对象类型之一的实例。现在,您可以调用该calAge方法。

function Person(name, birthday) {
  this.name = name;
  this.birthday = birthday;
};

Person.prototype.calAge = function () {
  console.log(2021 - this.birthday);
};

const rein = new Person("Rein", 1945);
rein.calAge();


推荐阅读