JavaScript 大概是現在最流行的跨平台語言之一,一直在玩前端一些有趣的東西,卻發現自己竟沒把這門語言掌握好,有點捨本逐末,於是趁現在有空好好補充一下遺漏的知識。
this 的隱性綁定
一開始這讓我很困惑,剛看到時無法理解,而後在相似情況下又能用類似方法解決同樣的問題,於是試著理清楚便於查找。
這是 JavaScript 語言設計上的一個特性。引用《JavaScript: The Good Parts》的例子:
復制代碼 代碼如下:
function add (a,b) {return a+b}
var sum = add (3,4);
console.log(sum); //sum = 7
此時 sum 的結果是 7。
復制代碼 代碼如下:
> typeof add
> 'function'
以此模式呼叫函式時,this 會被綁定到全域物件。也就是說,在目前的環境下,我們可以這樣呼叫:
復制代碼 代碼如下:
this.add(3,4)
這就是 this 的隱性綁定,而 this 會以不同方式被綁定:
復制代碼 代碼如下:
var hello = function (){
return "Hello, " + this.name;
};
name = 'this';
console.log(hello());
這時會得到 Hello, this。而當
復制代碼 代碼如下:
var hello = function (){
return "Hello, " + this.name;
};
var user = {
hello : hello,
name : 'phodal'
};
console.log(user.hello());
這時 user 中的 hello 便指向了 hello 函式,this 也隨之指向 user 物件。
如果我們在這個方法中定義一個變數並給它賦值 this,那麼內部函式就能透過那個變數存取 this。
var that = this
於是當情況稍微複雜一點時,我們就需要用到:
復制代碼 代碼如下:
var that = this;
tips:
1. this 變數的作用域總是由其最近的封閉函式所確定。
2. 使用一個局部變數(如 me、self、that)讓 this 綁定對內部可用。
一個簡單的例子:
復制代碼 代碼如下:
var M = function(){
this.name = "M";
};
var MM = function(){
z = new M();
this.name = "MM";
z.printName = function(){
console.log(this.name);
};
return z.printName();
};
var mm = new MM;
這時的 this 指向的是 M 函式,而非 MM 自身。如果我們把 M 中的 this 去掉,返回的就是一個 undefined。於是我們建立一個當前 this 作用域的別名,如 that 或 self:
復制代碼 代碼如下:
var MM = function(){
z = new M();
this.name = "MM";
var self = this;
z.printName = function(){
console.log(self.name);
};
return z.printName();
};
這樣就能返回 MM 了。除此之外,在 ES5 中可以用回調函式的 bind 方法:
復制代碼 代碼如下:
var MM = function(){
z = new M();
this.name = "MM";
z.printName = function(){
console.log(this.name);
}.bind(this);
return z.printName();
};
bind 可以將方法綁定到指定的接收者。
其他
又一次遇到 print('Hello')('World') 輸出 'Hello, World' 的情況。所謂的高階函式看起來似乎很有用,有興趣可以延伸閱讀相關主題。