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

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

Lighttpd

Lighttpd

Andre Bogus / Packt Publishing / 2008-10 / 39.99

This is your fast guide to getting started and getting inside the Lighttpd web server. Written from a developer's perspective, this book helps you understand Lighttpd, and get it set up as securely an......一起来看看 《Lighttpd》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具