javascript – 在类构造函数中定义一个const(ES6)

栏目: JavaScript · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/35242113/define-a-const-in-class-constructor-es6

参见英文答案 > Declaring static constants in ES6 classes? 9个

有没有办法在类的构造函数中定义一个const?

我试过这个:

class Foo {
    constructor () {
        const bar = 42;
    }

    getBar = () => {
        return this.bar;
    }
}

var a = new Foo();
console.log ( a.getBar() );

返回undefined.

您可以使用静态只读属性来声明作用于类的常量值.
class Foo {
    static get BAR() {
        return 42;
    }
}

console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error

翻译自:https://stackoverflow.com/questions/35242113/define-a-const-in-class-constructor-es6


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

jQuery

jQuery

Earle Castledine、Craig Sharkie / SitePoint / 2010-02-28 / USD 39.95

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most challenging JavaScript problems. In this question-and-answer book on jQuery, you'll find a cookbook of ready......一起来看看 《jQuery》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试