🍄class
🚧 under construction
Last updated
Was this helpful?
🚧 under construction
Last updated
Was this helpful?
Was this helpful?
creates a new class and gives it a name (identifier).
no commas between class member declarations❗
private member identifiers are prefixed with hash (#).
// ⭐️ class definition
class A {
// ⭐️ instance members (# means "private")
publicProp; // this.publicProp = undefined (by default)
publicMethod() { ... } // this.publicMethod()
#privateProp; // this.#privateProp
⭐ class declaration is not hoisted❗
⛔ cannot use a class before its declaration ❗(👉 )
a class's (property) is read-only❗
⭐️⭐️⭐️ you can change the of a function, but not that of a class.
⛔ ReferenceError: .
an error mostly caused by referencing a / / in its ❗
using on (/ / ) in its will throw a .
replit:
must be called with new.
methods are non-enumerable. (not enumerated in a for...in loop)
class body code always use strict.
function's scope is different from a block scope❗
// overwrite a function's prototype is OK
func.prototype = {} // ✅ OK
// overwrite a class's prototype won't work
Class.prototype = {} // ❌ won't work (ignored silently❗️)
// ⭐ temporal dead zone (start)
// ------------------------------
// typeof aLet; // ⛔ ReferenceError: Cannot access 'aLet' before initialization
// typeof aConst; // ⛔ ReferenceError: Cannot access 'aConst' before initialization
// typeof aClass; // ⛔ ReferenceError: Cannot access 'aClass' before initialization
typeof undeclared; // ❗ 'undefined'
// ⭐ lexical declarations (let/const/class)
// --------------------------------------------
let aLet; // ⭐ initialized to `undefined`
const aConst = "hello";
class aClass {}
// ⭐️ property/method/getter/setter 間都要用「逗號」隔開❗️
let user = {
name : "John", // ⭐️ 屬性間用「逗號」隔開
surname: "Smith",
set fullName(value) {
[this.name, this.surname] = value.split(" ");
}, // ⭐️ method/getter/setter 間也要用「逗號」隔開
get fullName() {
return `${this.name} ${this.surname}`;
}
};
// • (static/instance) "class fields".
// ❌ GAS 不支援
// ✅ 可用 (static/instance) getters/setters 代替.
let user = new User('Mary');
user.name = 'Joe'; // ⭐ setter: this._name = 'Joe'
user.sayHi(); // "hello"
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));