javascript - 创建对象的生命周期
问题描述
例子
class User {
constructor(firstname, lastName) {
this.firstname = firstname;
this.lastName = lastName;
}
getFullName() {
return `${this.firstname} ${this.lastName}`;
}
}
const user = new User('John', 'Doe');
console.log(user.getFullName());
User.prototype.getFullName = function() {
return 'CRASH!';
}
console.log(user.getFullName());
为什么从类创建对象后方法 getFullName 发生了变化?
我想在我创建对象之后它是另一个实体。
解决方案
根据https://medium.com/backticks-tildes/javascript-prototypes-ee46810e4866:
prototype
只是对另一个对象的引用,并包含该对象所有实例的通用属性/属性。当一个对象得到一个属性的请求时,它的原型会被搜索到该属性,然后是原型的原型,以此类推
在您的示例中,当您更改 User 类的原型时,它也会影响所有现有对象。
推荐阅读
- c# - 在 .NET Core 中全局强制设置不区分区域性的日期格式
- java - Google App Engine(Java 11 Standard,basic_scaling)idle_timeout 不起作用?
- django - 如何自定义 django rest auth 电子邮件上下文
- angular - 为什么我的订阅会在一个组件上触发一次,但在指向同一 observable 的其他组件上却可靠地触发?
- firebase - 未处理的异常:MissingPluginException(在通道 plugins.flutter.io/firebase_messaging 上找不到方法 getToken 的实现)
- mysql - java.sql.SQLNonTransientConnectionException:单体项目的 jhipster docker 生产中不允许公钥检索
- javascript - 错误:预期未定义等于业力
- mongodb - 如何使用 mongo-driver 使用 $elemMatch 查询 mongoDB
- python - 如何使用 Pandas 读取文件(带有特殊字符)?
- mysql - 由于“错误 1:无法准备语句(“IF”附近的 1:语法错误),SQL 无法更新表