1. 程式人生 > >全面理解JavaScript中的 this

全面理解JavaScript中的 this

全面理解JavaScript中的 this

上下文 VS 作用域

作用域(scope) 是在執行時程式碼中的某些特定部分中變數,函式和物件的可訪問性。換句話
說,作用域決定了程式碼區塊中變數和其他資源的可見性。而上下文
(context)是用來指定程式碼某些特定部分中 this 的值。

作用域是基於函式(function-based)的,而上下文是基於物件
(object-based)的。換句話說,作用域是和每次函式呼叫時變數的訪問有關,並且每次調 > 都是獨立的。上下文總是被呼叫函式中關鍵字 this 的值,是呼叫當前可執行程式碼的物件的 > 引用。說的通俗一點就是: this 取值,是在函式真正被呼叫執行的時候確定的,而不是在
函>數定義的時候確定的。

全域性物件

  • window
  • global

函式上下文

  • 全域性物件
  • 當前物件
  • 任意物件

作為函式直接呼叫

  • 非嚴格模式
function fun() {
    return this;
}

this === window  // browser
this === global // node.js
  • 嚴格模式 “use strict”

在嚴格模式下, this 將保持他進入執行上下文時的值,所以下面的 this 並不會指向全域性物件,而是預設為 undefined 。

'use strict';
function fun() {
    return this;
}

this === undefined //true

作為物件的方法呼叫

var obj = {
    name: "nicholas",
    getName:function () {
        return this.name;
    }
};
obj.getName() // "nicholas"

// 等價於

var obj = {
    name:"nicholas"
};
function getName() {
    return this.name;
}
obj.getname = getName;

作為建構函式呼叫

function Person(name) {
    this.name = name;
}
var p = new Person('nicholas');
console.log(p.name); // "nicholas" 

箭頭函式中的this

在箭頭函式中,this 與 封閉的詞法上下文的 this 保持一致,也就是說由上下文確定。

var obj = {
    x: 10,
    foo: function() {
        var fn = () => {
            return () => {
                return () => {
                    console.log(this);      //{x: 10, foo: ƒ} 即 obj
                    console.log(this.x);    //10
                }
            }
        }
        fn()()();
    }
}
obj.foo();

Reference

全面理解JavaScript中的 this