javascript - 为什么惰性 getter 使用原型(prototype)而不是类?

标签 javascript class ecmascript-6 setter getter

考虑以下代码:

const defclass = prototype => {
    const constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
};

const Person = defclass({
    constructor: function Person(firstname, lastname) {
        this.firstname = firstname;
        this.lastname  = lastname;
    },
    get fullname() {
        delete this.fullname; // doesn't delete on instances
        return this.fullname = this.firstname + " " + this.lastname;
    }
});

const john = new Person("John", "Doe");
const jane = new Person("Jane", "Doe");

console.log(john.fullname); // John Doe
console.log(jane.fullname); // Jane Doe

这是有效的,因为 this 上的属性赋值隐藏了不存在的 setter。


现在,考虑使用 ES6 类的相同代码:

class Person {
    constructor(firstname, lastname) {
        this.firstname = firstname;
        this.lastname  = lastname;
    }

    get fullname() {
        delete this.fullname; // doesn't delete on instances
        return this.fullname = this.firstname + " " + this.lastname;
    }
}

const john = new Person("John", "Doe");
const jane = new Person("Jane", "Doe");

console.log(john.fullname); // throws an error because there is no setter
console.log(jane.fullname);

它不起作用的原因在 this answer 中有解释。 .这是因为我们在原型(prototype)链中找到了属性,但它没有 setter。那么,为什么当我们使用常规原型(prototype)时不会抛出相同的错误?

注意:您可以使用 delete 关键字删除行而不影响代码的行为。

最佳答案

确实在第一个代码中遇到了同样的错误:

const defclass = prototype => {
    const constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
};

const Person = defclass({
    constructor: function Person(firstname, lastname) {
        this.firstname = firstname;
        this.lastname  = lastname;
    },
    get fullname() {
        "use strict";
//      ^^^^^^^^^^^^
        return this.fullname = this.firstname + " " + this.lastname;
    }
});

const john = new Person("John", "Doe");
const jane = new Person("Jane", "Doe");

console.log(john.fullname); // John Doe
console.log(jane.fullname); // Jane Doe

只是class代码在strict mode默认情况下。

在 sloppy 模式下,赋值不起作用但会被忽略,右边的值会从 getter 中return。再次访问 .fullname 将再次运行 getter。

关于javascript - 为什么惰性 getter 使用原型(prototype)而不是类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814728/

相关文章:

javascript - MutationObserver 和 window.onresize 永远不会停止,即使工作已完成

javascript - 多个组件状态的 react 钩子(Hook)没有更新

javascript - Jnotify jquery 插件用于 $_Get 消息

Jquery 是 (":visible") 在一个类上

python - 如何在不出现 MRO 错误的情况下动态添加 mixin 作为基类?

jquery - 我如何知道哪个元素有一个类?

angular - 如何在 Angular 应用程序中包含额外的 ES6 源代码

javascript - bootstrap scrollspy 上的简单缓动

javascript - 当插件事件被触发时,如何从 Backbone.js 中的 View 执行模型的函数?

javascript - 使用 if else 语句将谷歌地图添加到网页