iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
Modern Web

Vue.js Web Component 基礎以及 Vuex狀態管理 系列 第 8

Vue.js Web Component 基礎以及 Vuex狀態管理 第八天 Vue.js how to work with this

Vue.js how to work with this

Javascript 中的 this 指向是使用情境的上下文相關,

舉例來說:

<button onClick="clickHandler(this)"></button>
function clickHandler(currentObj){
    console.log(currentObj);
}

src code

上面範例之中,當 onClick 事件被觸發時傳入的 this

就會是 clickHandler 所處在的 DOM 也就是

<button onClick="clickHandler(this)"></button>

參考文件: arrow function with this

參考文獻:arrow function 所影響到this

在使用 Vue.js 時,Component 內的 methods 如果是不使用箭頭函數,

這時在 methods 內使用 this 對應的到的就是 Component 對應的 Vue Instance

而如果使用箭頭函數,由於箭頭函數會讓 this 指向更上一層的呼叫者

因為箭頭函數並無自己的 this 只會承襲致上一層的 this。

因此,這時 methods 內使用的 this 就會對應到 window 這個 global 物件


上一篇
Vue.js Web Component 基礎以及 Vuex狀態管理 鐵人賽 第七天 Vuex State management
系列文
Vue.js Web Component 基礎以及 Vuex狀態管理 8
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言