I am learning classes in JS, and I have tried to see how static get
works. From reading about it, I thought this would work:
class Builder {
constructor() {
this.number = 1;
}
static get increaseNumber() {
return 1 + this.number;
}
}
const builderInstance = new Builder();
But, I get undefined
when I try to run this:
console.log(builderInstance.increaseNumber);
If I remove the static
keyword then it works, why do I get undefined
if I use static
?
I am learning classes in JS, and I have tried to see how static get
works. From reading about it, I thought this would work:
class Builder {
constructor() {
this.number = 1;
}
static get increaseNumber() {
return 1 + this.number;
}
}
const builderInstance = new Builder();
But, I get undefined
when I try to run this:
console.log(builderInstance.increaseNumber);
If I remove the static
keyword then it works, why do I get undefined
if I use static
?
2 Answers
Reset to default 3You get undefined because increaseNumber
is static and you try to call it from an instance of Builder
.
static
is a keyword
stating that the method will be callable by the class.
You cannot call a static method directly from the object.
here is a tutorial explaining it
class Builder {
constructor() {
this.number = 1;
}
static get increaseNumber() {
return 1 + this.number;
}
}
const builderInstance = new Builder();
console.log(builderInstance.increaseNumber);
Here is the appropriate implementation to call from an object :
An object represent an instance of a class
class Builder {
constructor() {
this.number = 1;
}
get increaseNumber() {
return 1 + this.number;
}
}
const builderInstance = new Builder();
console.log(builderInstance.increaseNumber);
As you asked me from the ment, the following snippet returns NaN
, why ?
class Builder {
constructor() {
this.number = 1;
}
static get increaseNumber() {
return 1 + this.number;
}
}
console.log(Builder.increaseNumber);
Because you try to access to a property called number
; which is undefined
and 1 + undefined
equals NaN
.
When calling the static method, you are not executing the constructor
and so the number is not initialized.
What you can do :
class Builder {
static get increaseNumber() {
// We use || here to say "if it's not initialized, initialize it to 0"
this.number = (this.number || 0) + 1;
return this.number;
}
}
console.log(Builder.increaseNumber);
console.log(Builder.increaseNumber);
console.log(Builder.increaseNumber);
console.log(Builder.increaseNumber);
Like other languages with static class members, the static keyword will create a method associated with the class, and not with an instance of the class. In other words,
you can only reach a static method using the name of the class
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744861721a4597740.html
评论列表(0条)