JS getter

Encountered with the following function as below:

1
2
3
4
5
6
7
8
9
10
static get userFilter() {
return {
dataset1: {
value: '...'
},
dataset2: {
value: '...'
}
};
}

so question comes up: Whats the meaning of ‘static get’ in Javascript (ES6)?

According to the above answer,

  • static defines that this function inside class is static, which means you cannot call the func via the instance of the class

    1
    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 function

    Lookup: Static method | Class的基本语法 2.静态方法

  • get syntax binds an object property to a function that will be called when is property is looked up

    1
    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 latest for object obj, which will return the last array item in log, but the attempt to assign a value to latest will not change it.
    For more details, see MDN>JavaScript reference>Functions>getter