this 在**函式執行時**決定,取決於**呼叫方式**,而非定義位置。
var name = "window";
function foo() { console.log(this.name); }
foo(); // "window" (非嚴格模式)
// 嚴格模式 'use strict' 下為 undefined
this → 全域物件 (window)
var obj = { name: "obj", foo: function() { console.log(this.name); } };
obj.foo(); // "obj"
this → 呼叫物件 (obj)
function Foo() { this.name = "instance"; console.log(this); }
new Foo(); // Foo { name: "instance" }
this → 新建立的實例物件
var obj = {
name: "obj",
outer: function() {
console.log(this.name); // "obj"
function inner() { console.log(this.name); } // 內部函式
inner(); // "window" (非嚴格模式)
}
};
obj.outer();
解決: 使用箭頭函式、var self = this、或 .bind(this)
// 箭頭函式(ES6,推薦)
var obj = {
name: "obj",
outer: function() {
var inner = () => console.log(this.name); // 繼承外層 this
inner(); // "obj"
}
};
function greet(greeting) { console.log(greeting + ", " + this.name); }
var a = { name: "A" }, b = { name: "B" };
greet.call(a, "Hello"); // "Hello, A" - 參數列表
greet.apply(b, ["Hi"]); // "Hi, B" - 參數陣列
var bound = greet.bind(a, "Hey");
bound(); // "Hey, A" - 回傳綁定後的新函式
| 綁定方式 | this 指向 | 備註 |
|---|---|---|
HTML 內聯 onclick="fn()" | window | 函式在全域執行上下文 |
DOM 屬性 el.onclick = fn | 元素 | 標準行為 |
el.addEventListener('click', fn) | 元素 | 標準行為 |
el.attachEvent('onclick', fn) (IE) | window | IE 舊模式特例 |
jQuery $(el).click(fn) | 元素 | jQuery 內部用 call 綁定 |
箭頭函式 el.addEventListener('click', () => ...) | 外層 this | 箭頭函式無 this,繼承詞法環境 |