在寫JS程式碼時,this的出場頻率頗高,擔負了傳遞物件,作用域等等功能,堪稱全能超人。

“我是誰?我從哪來?我要到哪去?”


示例程式碼
例1:
// 瀏覽器中
console.log(this);
複製程式碼

例2:
// Node.js cli中
console.log(this);
複製程式碼

// Node.js module中
// 具體原因可檢視Node模組作用域知識
//main.js
console.log(this === global);
console.log(this === module.exports);
複製程式碼

例3:
//瀏覽器中
function foo() {
console.log(this);
}
foo();
複製程式碼

//瀏覽器中
function foo() {
"use strict";
console.log(this);
}
foo();
複製程式碼

例5:
// 瀏覽器中
var _this;
function Foo() {
_this = this;
}
var foo = new Foo();
console.log(_this);
foo === _this;
複製程式碼

例6:
// 瀏覽器中
var foo = {
method: function() {
console.log(this === foo);
}
}
foo.method();
複製程式碼

例7:
// 瀏覽器暫不支援ES6語法,在Node 8.0以上版本試驗
// test.js
function foo() {
let bar = () => {
console.log('from bar->' + this);
};
console.log('from foo->' + this)
bar();
// 箭頭函式免疫call/apply修改作用域
bar.call(666);
}
foo.call(555);
foo.call(777);
複製程式碼

下一次總結this常見的陷阱及避坑建議( ̄. ̄)