| 包裝類 | typeof 結果 | 典型值 | 分類 |
|---|---|---|---|
| Number | "number" | 123.45 | 基本型別 |
| Boolean | "boolean" | true/false | |
| String | "string" | "hello" | |
| Object | "object" | {}, [] | 複合型別 |
| Function | "function" | function(){} | |
| 無 | "undefined" | undefined | 特殊型別 |
| 無 | "object" (Bug) | null |
let a = {x:1}, b = a; b.x = 2; console.log(a.x); // 2 (共享同一對象)
let p = 10, q = p; q = 20; console.log(p); // 10 (獨立副本)
function ClassName() { this.id = 0; }
const v = new ClassName();
內部 5 步驟:
ClassName.prototype,淺拷貝其屬性到新對象this 綁定新對象this.constructor = ClassNamethis 賦予左值註:ClassName.prototype.constructor 默認也指向 ClassName,步驟 3 實例屬性覆蓋原型屬性。
function ClassName(a) {
// 私有:僅構造函數作用域可訪問
let uid = a;
// 特權方法:訪問私有變量的公共接口
this.getUid = () => uid; // 只讀
this.setUid = (val) => { uid = val; }; // 可寫
// 公共屬性
this.id = uid;
}
// 原型方法:公共行為
ClassName.prototype.func = function() { ... };
// 靜態屬性/方法:屬於構造函數本身
ClassName.staticProp = "static";
ClassName.staticMethod = function() { ... };
function Parent(name) {
this.name = name;
this.colors = ["red", "blue"];
}
Parent.prototype.sayName = function() { console.log(this.name); };
function Child(name, age) {
Parent.call(this, name); // 盜用構造函數:繼承實例屬性 (含引用類型獨立副本)
this.age = age;
}
// 原型鏈繼承方法
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 子類擴展
Child.prototype.sayAge = function() { console.log(this.age); };
const child = new Child("Tom", 10);
child.sayName(); // "Tom"
child.colors.push("green"); // 不影響 Parent.prototype.colors
console.log(child.colors); // ["red", "blue", "green"]
class Animal {
speak() { console.log("Animal sound"); }
}
class Dog extends Animal {
speak() { console.log("Woof"); } // 重寫
}
class Cat extends Animal {
speak() { console.log("Meow"); }
}
function makeSpeak(animal) {
animal.speak(); // 運行時根據實際類型調用
}
makeSpeak(new Dog()); // "Woof"
makeSpeak(new Cat()); // "Meow"
class Person {
#privateField = "secret"; // 真私有 (Stage 3)
constructor(name, age) {
this.name = name;
this.age = age;
}
// 實例方法 (自動定義在 prototype)
greet() {
console.log(`Hi, I'm ${this.name}, ${this.age}`);
}
// 存取器
get info() { return `${this.name} (${this.age})`; }
set info(val) { [this.name, this.age] = val.split(" "); }
// 靜態方法
static species() { return "Homo sapiens"; }
}
class Employee extends Person {
constructor(name, age, dept) {
super(name, age); // 必須先調用 super()
this.dept = dept;
}
// 重寫
greet() {
super.greet(); // 呼叫父類方法
console.log(`Dept: ${this.dept}`);
}
}
new() => this.method() 或 .bind(this)const user = Object.assign({}, authMixin, logMixin)Object.freeze()、Readonly<T> (TS)、Immer 庫Array.prototype.xxx = ... 污染全局,極易衝突