this

參考文章

  • 淺談 JavaScript 頭號難題 this:絕對不完整,但保證好懂arrow-up-right

    • JavaScript 裡的 this (在任何地方都可以存取到 this)跟其他程式語言慣用的那個 this (它代表的就是在物件導向裡面,那個 instance 實例本身。)有差異

    • 區分

      1. 嚴格模式底下就都是undefined

      2. 非嚴格模式,瀏覽器底下是window

      3. 非嚴格模式,node.js 底下是global

    • 總結

      1. 在物件以外的 this 基本上沒有任何意義,硬要輸出的話會給個預設值

      2. 可以用 call、apply 與 bind 改變 this 的值:如下

'use strict';
function hello(a, b){
  console.log(this, a, b)
}

hello(1, 2) // undefined 1 2
hello.call(undefined, 1, 2) // undefined 1 2
hello.apply(undefined, [1, 2]) // undefined 1 2

'use strict';
function hello(a, b){
  console.log(this, a, b)
}

hello.call('yo', 1, 2) // yo 1 2
hello.apply('hihihi', [1, 2]) // hihihi 1 2

'use strict';
function hello() {
  console.log(this)
}

const myHello = hello.bind('my')
myHello() // my
  • this · 從ES6開始的JavaScript學習生活arrow-up-right

    • this的指向的是目前呼叫函式或方法的擁有者(owner)物件,也就是說它與函式如何被呼叫或調用有關

    • 對this值來說,它根本不關心函式是在哪裡定義或是怎麼定義的,它只關心是誰呼叫了它。

Last updated