function fn() {
alert('函數宣告');
}
fn(); // 可在宣告前呼叫(提升 Hoisting)
const fn = function () {
alert('函數運算式');
};
fn(); // 必須在定義後呼叫
const sum = new Function('a', 'b', 'return a + b;');
console.log(sum(1, 2)); // 3
構造函數慣用**大寫開頭**,配合 new 關鍵字建立實例:
function Person(name) {
this.name = name; // 實例屬性
this.sayHi = function () { // 實例方法(每個實例獨佔一份)
alert('Hi, ' + this.name);
};
}
Person.prototype.getName = function () { // 原型方法(共享)
return this.name;
};
const p1 = new Person('Alice');
const p2 = new Person('Bob');
p1.sayHi(); // Hi, Alice
console.log(p1.getName()); // Alice
console.log(p1.sayHi === p2.sayHi); // false(各自擁有副本)
console.log(p1.getName === p2.getName); // true(共享原型)
| 概念 | 說明 |
|---|---|
| this | 在構造函數中指向新建立的實例 |
| prototype | 函數的屬性,指向原型物件,所有實例共享 |
| __proto__ | 實例的內部屬性,指向建構函數的 prototype |
| constructor | 原型物件上的屬性,指回建構函數 |
| new 操作 | 1.建立空物件 2.綁定原型 3.執行構造函數 4.回傳物件 |
class Person {
constructor(name) {
this.name = name;
}
sayHi() { alert(`Hi, ${this.name}`); }
static species = 'Human'; // 靜態屬性
static createAnonymous() { return new Person('Anonymous'); }
}
const p = new Person('Charlie');
Person.createAnonymous(); // 靜態方法
Class 本質仍是原型繼承,語法更清晰、支援 extends / super。
prototype、無 this 綁定)。new 直接呼叫構造函數會污染全域物件(嚴格模式下拋錯)。