Encountered with the following function as below:
1 | static get userFilter() { |
so question comes up: Whats the meaning of ‘static get’ in Javascript (ES6)?
According to the above answer,
staticdefines that this function inside class is static, which means you cannot call the func via the instance of the class1
2
3
4
5
6
7
8
9
10
11
12
13
14// e.g.
class Agent {
static get CIRCLE() {
return 1;
}
static get SQUARE() {
return 2;
}
}
// you call this as a property directly
Agent.CIRCLE; // 1
// but call by an instance is not allowed
const newAgent = new Agent();
console.log(newAgent.CIRCLE); // undefined or TypeError: foo.classMethod is not a functionLookup: Static method | Class的基本语法 2.静态方法
getsyntax binds an object property to a function that will be called when is property is looked up1
2
3
4
5
6
7
8
9// e.g.
const obj = {
log: ['example','test'],
get latest() {
if (this.log.length === 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // "test".Note: the above code will create a pseudo-property
latestfor objectobj, which will return the last array item inlog, but the attempt to assign a value tolatestwill not change it.
For more details, see MDN>JavaScript reference>Functions>getter