javascript - 使用 Class 声明原型(prototype)默认值的 ecmascript 6 语法

标签 javascript ecmascript-6 prototype es6-class

在 javascript 中创建类时,您可以通过访问函数的 prototype 来设置默认值。

    function Foo() {
    }
    Foo.prototype.get = function() {
        return this._value;
    }
    Foo.prototype._value = 'foo value';
    var foo = new Foo();
    console.log(foo.get()); // logs "foo value"

如何使用 ecmascript 6 class 实现类似的效果?

    // this doesn't work
    class Bar {
        get() {
            return this._value;
        }
        // how to declare following default value properly?
        _value: "bar value"
    }
    var bar = new Bar();
    console.log(bar.get()); // logs undefined

最佳答案

class 语法只允许您定义方法,但它仍然只是创建一个带有 .prototype 对象的构造函数。您可以像在 ES5 中一样设置默认值:

// this does work
class Bar {
    get() {
        return this._value;
    }
}
Bar.prototype._value = 'foo value';
var bar = new Bar();
console.log(bar.get()); // logs 'foo value'

当然,您可能只想创建和初始化一个实例属性:

// this does work
class Bar {
    constructor() {
        this._value = 'foo value';
    }
    get() {
        return this._value;
    }
}
var bar = new Bar();
console.log(bar.get()); // logs 'foo value'

另一种已变得相当普遍的解决方案是使用 getter,它将在原型(prototype)上定义,这当然有一个缺点,即在每次访问属性时都会创建该值:

class Bar {
    get() {
        return this._value;
    }
    get _value() {
        return 'foo value';
    }
}

如果您坚持只使用class 语法,ES2022 will have static blocks这也可能被滥用来创建原型(prototype)属性:

class Bar {
    get() {
        return this._value;
    }
    static {
        this.prototype._value = 'foo value';
    }
}

关于javascript - 使用 Class 声明原型(prototype)默认值的 ecmascript 6 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185643/

相关文章:

javascript - 等待发送请求,但不使用 Javascript Promise 进行响应

javascript - 如何添加多个 Angular 验证规则并使用 ng :invalid

javascript - 使用 JS 动态地将 SVG 放置在视口(viewport)中间

reactjs - 从另一个选择选项更新选择 react

javascript - 在子组件中键入 useState setter

JavaScript - 基于原型(prototype)的编程 - this.myFunction 不是函数错误

javascript - Form.submit 在 FF 和 IE 中不起作用

callback - 外来控制流的 ES6 Promise 模式

javascript - 如何扩展 Array.prototype.push()?

从没有自定义头文件的多个 C 文件调用方法,Makefile 链接