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

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

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


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

查看所有标签

猜你喜欢:

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

PHP and MySQL Web Development (3rd Edition) (Developer's Library

PHP and MySQL Web Development (3rd Edition) (Developer's Library

Luke Welling、Laura Thomson / Sams / 2004-09-29 / USD 49.99

We've taken the best and made it even better. The third edition of the best-selling PHP and MySQL Web Development has been updated to include material and code on MySQL 5, PHP 5 and on PHPs object mod......一起来看看 《PHP and MySQL Web Development (3rd Edition) (Developer's Library》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具