JavaScript ES6 类中的私有属性 [英] Private properties in JavaScript ES6 classes
本文介绍了JavaScript ES6 类中的私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 ES6 类中创建私有属性?
Is it possible to create private properties in ES6 classes?
这是一个例子.如何阻止对 instance.property
的访问?
Here's an example.
How can I prevent access to instance.property
?
class Something {
constructor(){
this.property = "test";
}
}
var instance = new Something();
console.log(instance.property); //=> "test"
推荐答案
私人课程功能在第3阶段提案中.其大部分功能支持所有主要浏览器.
Private class features is in Stage 3 proposal. The majority of its features are supported by all major browsers.
class Something {
#property;
constructor(){
this.#property = "test";
}
#privateMethod() {
return 'hello world';
}
getPrivateMessage() {
return this.#property;
}
}
const instance = new Something();
console.log(instance.property); //=> undefined
console.log(instance.privateMethod); //=> undefined
console.log(instance.getPrivateMessage()); //=> test
console.log(instance.#property); //=> Syntax error
这篇关于JavaScript ES6 类中的私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文