var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
};
}
};
var A = Class.create();
A.prototype = {
initialize: function(v) { this.value = v; },
showValue: function() { alert(this.value); }
};
var a = new A('helloWorld!');
a.showValue(); // 彈出 helloWorld!
這段代碼涉及:構造函數、原型鏈、`apply`、`arguments`、`this` 指向。下面逐層拆解。
var Person = function(name) {
this.name = name; // 實例屬性
this.sayHi = function() { // 實例方法(每個實例擁有副本)
alert(this.name);
};
};
var p1 = new Person('Tom'); // p1 是 Person 實例,構造函數內 this 指向 p1
var p2 = Person('Jerry'); // 無 new,當作普通函數執行,this 指向 window → 污染全局
Person.prototype.sayHi = function() { // 所有實例共享同一個函數
alert(this.name);
};
var p3 = new Person('Bob');
p3.sayHi(); // Bob
function() {
this.initialize.apply(this, arguments);
}
約定俗成的「構造器初始化方法」,在 `A.prototype` 中定義:
initialize: function(v) { this.value = v; }
因此 `new A('hello')` 相當於執行 `a.value = 'hello'`。
| 方法 | 語法 | 參數傳遞 | 適用場景 |
|---|---|---|---|
call | fn.call(thisArg, arg1, arg2, ...) | 逐個列舉 | 參數數量固定、明確 |
apply | fn.apply(thisArg, [argsArray]) | 數組/類數組 | 參數數量不定、已有數組 |
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
var person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // Hello, Alice!
greet.apply(person, ['Hi', '?']); // Hi, Alice?
// 經典應用:數組求最大值
var max = Math.max.apply(null, [1, 5, 3]); // 5
function test() {
console.log(typeof arguments); // "object"
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
test("1", "2", "3"); // 依次輸出 1 2 3
| 概念 | 含義 | 典型用法 |
|---|---|---|
this | 函數執行時的上下文對象,由**調用方式**決定 | 構造函數、方法調用、事件處理器、call/apply/bind 綁定 |
self | **非關鍵字**,慣例變量名,用於在閉包/回調中保存外層 `this` | `var self = this;` 在異步回調、定時器、事件處理器中訪問外層上下文 |
var obj = {
name: 'Outer',
asyncFunc: function() {
var self = this; // 保存外層 this
setTimeout(function() {
console.log(self.name); // 'Outer' (若直接用 this 會指向 window)
}, 100);
}
};
obj.asyncFunc();
現代寫法:箭頭函數自動捕獲外層 `this`,無需 `self`:
asyncFunc: function() {
setTimeout(() => {
console.log(this.name); // 箭頭函數無 this,沿用外層
}, 100);
}
new A('hello')
│
▼
創建新對象 a,a.__proto__ = A.prototype
│
▼
執行構造函數:function() { this.initialize.apply(this, arguments); }
│
▼
this → a
arguments → ['hello']
│
▼
a.initialize.apply(a, ['hello'])
│
▼
initialize 內部:this.value = 'hello' → a.value = 'hello'
│
▼
返回 a(隱式)