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


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

查看所有标签

猜你喜欢:

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

The Photoshop Anthology

The Photoshop Anthology

Corrie Haffly / SitePoint Pty. Ltd. / 2006 / USD 39.95

The Photoshop Anthology is full-color, question-and-answer book for Web Designers who want to use Photoshop to build Websites and create better looking web graphics more effectively. The book covers: ......一起来看看 《The Photoshop Anthology》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换