javascript - 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();
它不起作用。但函数也是对象。一个对象也有一个原型。
那么为什么第二个例子不起作用呢?
解决方案
我认为您的意思是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();
推荐阅读
- opengl - 如何在 Racket 中制作可编程管道 OpenGL 上下文
- angularjs - 如何获取“父名称”并读取 ng-repeat AngujarJs 中的对象?
- kubernetes - Kubernetes 和就绪探针
- mysql - 拒绝访问我有权访问的数据库
- react-native - Null 不是 React Native 路由中的对象
- hibernate - 如何使用 JPQL 查询减少查询执行时间
- regex - 正则表达式不排除python案例
- haskell - 调用 newtype 构造函数
- android-studio - 我可以在 Android Studio IDE 中输入 Git 命令吗?
- python - 如何从该模型中获取对象?