this
物件:
一般模式下:Global 物件。 嚴謹模式下:undefined
this
會是 undefined
。節錄 W3Schools 的原文:
When used alone, the owner is the Global object. The Global object (the owner of the function) is the default binding. Strict mode does not allow default binding.
this
會綁定 Global 物件,在 HTML 環境裡就是 window
物件:this
不會作預設綁定,會是 undefined
:obj.f()
內再定義一個內部函數 foo()
,進行內部呼叫。foo()
沒有指定呼叫物件,this
就是 Global 物件,因此 foo()
所印出的 this.x
值會是全域變數的 x
,而非 obj
的 x
(Output 2)。foo()
可以取到obj.x
,可以使用一個變數去儲存執行 obj.f()
時的 this
物件。this
物件:接受該事件的 HTML 元素 (HTML Element)。
this
就是該事件的 HTML 元素。onclick
裡的 this
,指的就是 <button>
元素本身。this
物件:新函數物件被指定的綁定物件,也就是Function.prototype.bind()
的第一個參數。
Function.prototype.bind
,可以為一個函數建立一個繼承該函數 prototype 的新函數物件,但綁定一個固定的擁有者。this
都會是當初綁定的那個擁有者物件。Function.prototype.bind
的綁定,一般模式或嚴謹模式是一樣的結果。getFullName()
:getFullName()
,也是上面 2.1 節所舉的情境。this
值。firstName
和 lastName
,因而印出 "One Jar"
。getFullName().bind()
,分別產生了兩個新的函數物件,繼承了 getFullName()
的 prototype,但各自綁定了固定的擁有者物件。introIronMan
函數物件綁定了擁有者物件 { firstName: "Tony", lastName : "Stark" }
。introCaptainAmerica
函數物件綁定了擁有者物件 { firstName: "Steven", lastName : "Rogers" }
。introIronMan()
和 introCaptainAmerica()
,函數內的 this
值會是各自當初綁定的物件 (而非 Global 物件)。getFullName()
時,因為是嚴謹模式,this
不再預設綁定 Global 物件,因此是 undefined
(2.1 節情境)。introIronMan()
和 introCaptainAmerica()
不受影響。Function.prototype.bind
所建立的新函數物件 A,如果企圖用 Function.prototype.bind
再去建立一個新函數物件 B 並綁定新擁有者,因為函數物件 B 繼承了 A 的 prototype,包含當初的綁定者,因此無論是否給予新的綁定對象都沒有用。