JS ⟩ value ⟩ object ⟩ class ⟩ member
Copy const { log } = console;
// ⭐️ class definition
// --------------------------------------------------------
// ❌ GAS doesn't support (static/instance) "class fields".
// ✅ GAS does support "static methods/getters/setters".
class User {
// -------------------------
// ⭐️ static members
class 定義背後有幾個分解動作:
也就是說,透過 class 語法宣告的 Animal,其實是宣告了一個 function Animal,與一個 Animal.prototype (在 class body 內定義的方法都放在這裡)。
// -------------------------
// ❌ GAS 不支援 (static) "class fields".
// ✅ 可用 static getters/setters 代替.
static planet = "Earth" ; // static property
// ✅ GAS 支援 "(static) methods/getters/setters".
static staticMethod () { // static method
return 'static method'
}
// -----------------------------------------------------
// ⭐️ static getters/setters as static properties
// -----------------------------------------------------
// ✅ GAS 可用這個來代替 static class fields.
static get age () { return this ._age } // getter
static set age (value) { // setter
if (value < 0 ) { log ( `age cannot be negative: ${ value } ` ); return ; }
this ._age = value
}
// -------------------------
// ⭐️ class fields
// -------------------------
// ❌ GAS 不支援 "class fields".
// ✅ 可用 getters/setters 代替.
age = 0 ; // regular class field
hobby = prompt ( 'any hobby?' , "game" ); // ⭐️ function value as property value
boundMethod = () => { }; // 🔗 bound method (`this` === instance)
// -------------------------
// ⭐️ getters/setters
// -------------------------
// ✅ GAS 可用這個來代替 instace class fields.
get name () { return this ._name } // getter
set name (value) { // setter
this ._name = value
}
// -----------------
// ⭐️ methods
// -----------------
constructor () { } // ⭐️ constructor
method () { } // regular method
[ 'say' + 'Hi' ]() { log ( `hello` ) } // ⭐ computed-name method
}
// test code
let user = new User ( 'Mary' );
user .name = 'Joe' ; // ⭐ setter: this._name = 'Joe'
user .sayHi (); // "hello"
// test static getter/setter
User .age = - 9 ; // "age cannot be negative: -9"
User .age = 10 ;
[
user .name , // "Joe"
user .hobby ,
user .planet , // undefined
User .planet , // "Earth"
User .staticMethod () , // "static method"
User .age , // 10
] .forEach (x => log (x));
// ⭐️ class expression
// ---------------------------------------------------------------
let User2 = class {
sayHi () {}
};
// ⭐️ class expression as return value
// ---------------------------------------------------------------
function returnUserClass (){
return class {
sayHi () {}
};
}
Copy object prototype chain (.__proto__)
-----------------------------------------
Animal Function.prototype
Rabbit Animal.prototype
Animal.prototype Object.prototype
Rabbit.prototype Animal.prototype