我如何在JS构造函数之外设置属性,就像在Java中一样?



如果我不想在Java中实例化类时初始化类的所有属性,可以这样做:

class Example {
Example(int property1){
this.setProperty1(property1);
}
int property1;
int property2;
getProperty1(){
return this.property1;
}
setProperty1(int property1){
this.property1 = property1;
}
getProperty2(){
return this.property2;
}
setProperty1(int property2){
this.property2 = property2;
}
}

在这种情况下,我不想在实例化Example类时立即初始化property2

我的问题是如何使用JS类实现相同的行为,因为在我的情况下,以下是不工作,我不能设置值到chaveDeAcesso属性:

(顺便说一句:我在vscode上使用ESLint和Airbnb风格指南)

class NotaFiscal {
constructor(indexNotaFiscal) {
this.indexNotaFiscal = indexNotaFiscal;
}
chaveDeAcesso;
get chaveDeAcesso() {
return this.chaveDeAcesso;
}
set chaveDeAcesso(chaveAcesso) {
this.chaveDeAcesso = chaveAcesso;
}
}

类内部的消息显示

Javascript的setter和getter与Java不同。典型的模式是使用下划线_chaveDeAcesso定义实例变量,然后允许使用setter和getter访问该实例变量,而不使用下划线,如下面的代码所示。这些方法在原型上,可以像这样访问:

this.chaveDeAcesso=3; //call the setter when you write
let x = this.chaveDeAcesso; //cal the getter when you read

class NotaFiscal {
_chaveDeAcesso;
constructor(indexNotaFiscal) {
this.indexNotaFiscal = indexNotaFiscal;
}

get chaveDeAcesso() {
return this._chaveDeAcesso;
}
set chaveDeAcesso(chaveAcesso) {
this._chaveDeAcesso = chaveAcesso;
}
}
let x = new NotaFiscal(1);
console.log(x._chaveDeAcesso);
x.chaveDeAcesso=5;
console.log(x._chaveDeAcesso);

进一步注意,像这样定义的_chaveDeAcesso不是私有的,并且在构造函数之外这样定义它是一个实验特性(例如,您必须使用babel在es6中编译它),这可能是错误的原因。您可以在构造函数中定义它而不初始化它(这是多余的,即使省略它,它仍然是未定义的)。插入只是为了使代码更具可读性。)无论哪种情况,它都是未定义的:

constructor(indexNotaFiscal) {
this.indexNotaFiscal = indexNotaFiscal;
this._chaveDeAcesso = undefined; //unnecessary instruction, is already undefined. 
}

相关内容

  • 没有找到相关文章

最新更新