call、apply、bind的基本使用

基本使用

call、apply、bind的核心功能都是改變函數的this指向,但彼此之間也有一些差別。

call

改變this指向且執行函數,額外參數以參數列表形式傳入


let context = {
    name:'神祕的寶爺'
}

const myFn = function(age,height){
    console.log(this.name+':'+age+':'+height)
}

myFn.call(context,25,'180cm')  // 神祕的寶爺:25歲:180cm

複製代碼

apply

與call幾乎一樣改變this指向且執行函數,額外參數以數組形式傳入


let context = {
    name:'神祕的寶爺'
}

const myFn = function(age,height){
    console.log(this.name+':'+age+':'+height)
}

myFn.call(context,[25,'180cm'])  // 神祕的寶爺:25歲:180cm

複製代碼

bind

改變this指向,的函數,而是返回一個this被改變的function,參數以參數列表形式傳入


let context = {
    name:'神祕的寶爺'
}

const myFn = function(age,height){
    console.log(this.name+':'+age+':'+height)
}

let myFn2  = myFn.bind(context)

myFn2(25,'180cm') // 神祕的寶爺:25歲:180cm

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章