gpt4 book ai didi

javascript - ECMAScript 2015 类中不允许使用哪些代码?

转载 作者:行者123 更新时间:2023-12-03 02:12:18 24 4
gpt4 key购买 nike

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance

ECMAScript 2015 类 {} 括号内不允许使用什么类型的代码?私有(private)变量、常量和函数可以在class括号内声明吗?

例如

class Person{
constructor(n){ this.name = n;}
const HELLO = 'Hello!'; //is this allowed?
saySomething (m){ console.log(this.name + ' says ' + (m || HELLO)) }
}

最佳答案

根据this article ,基本类语法如下所示:

class MyClass {
constructor(...) {
// ...
}
method1(...) {}
method2(...) {}
get something(...) {}
set something(...) {}
static staticMethod(..) {}
// ...
}

所提供的示例代码将在 Chrome 上抛出 Uncaught SyntaxError: Unexpectedidentifier 错误; private constvarclass 声明中不允许。一种替代方法是使用 IIFE (立即调用函数表达式):

Person = (function(){

const HELLO = 'Hello!';

class Person{
constructor(n){ this.name = n;}
saySomething (m){ console.log(this.name + ' says ' + (m || HELLO))
}

return Person;
})();

有关更多详细信息,请参阅ECMAScript 2015 classes规范。

关于javascript - ECMAScript 2015 类中不允许使用哪些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com