首页 > 解决方案 > 创建对象的生命周期

问题描述

例子

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 发生了变化?

我想在我创建对象之后它是另一个实体。

标签: javascript

解决方案


根据https://medium.com/backticks-tildes/javascript-prototypes-ee46810e4866

prototype只是对另一个对象的引用,并包含该对象所有实例的通用属性/属性。当一个对象得到一个属性的请求时,它的原型会被搜索到该属性,然后是原型的原型,以此类推

在您的示例中,当您更改 User 类的原型时,它也会影响所有现有对象。


推荐阅读