讓 function 決定 this 是誰,並更改 "傳入物件" 下的資料,而這個物件也可以是動態產生的,不用 var 或 let,這樣感覺蠻彈性的,但應該會不容易閱讀。
這方法我還蠻少用的,可能是物件導向的概念或是專案複雜度的關係,也沒這個需求,所以就知道一下這方法囉~
透過物件去改資料或是根本就是兩個物件帶著不同資料
call, apply, bind 都可以讓 function 改變傳入物件的資料
以下是 call 方法
要填入參數的寫法
apply 方法跟 call 一樣,差傳入資料要包在陣列裡,這樣的好處是可以傳入多的參數,而不用改原來 function 的接口
bind 僅是更換 this,沒有執行換資料
僅要一行 code 就能更換 this 很方便使用呢!
但習慣用物件導向的方式處理,還是可以用在 class 身上就是了,只是這不透過 get / set 的方式,不是很習慣就是了
參考 https://ithelp.ithome.com.tw/articles/10195896
參考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
這方法我還蠻少用的,可能是物件導向的概念或是專案複雜度的關係,也沒這個需求,所以就知道一下這方法囉~
透過物件去改資料或是根本就是兩個物件帶著不同資料
class User {
constructor(name) { this.name = name || 'leo'; }
sayHi() { return `hi! ${this.name}`; }
}
var user = new User()
log( user.sayHi() ) // hi! leo
user = new User('power')
log( user.sayHi() ) // hi! power
call, apply, bind 都可以讓 function 改變傳入物件的資料
以下是 call 方法
var user = {
name: 'leo',
sayHi: function() { return `hi! ${this.name}`; }
}
log( user.sayHi() ) // hi! leo
log( user.sayHi.call({ name: 'power' }) ) // hi! frank
要填入參數的寫法
var user = {
name: 'leo',
sayHi: function(msg) { return `hi! ${this.name} ${msg}`; }
}
log( user.sayHi.call({ name: 'power' }, ', how are you today') )
// hi! frank, how are you today
apply 方法跟 call 一樣,差傳入資料要包在陣列裡,這樣的好處是可以傳入多的參數,而不用改原來 function 的接口
var user = {
name: 'leo',
sayHi: function(msg) { return `hi! ${this.name} ${msg}`; }
};
log(user.sayHi.apply({ name: 'moss' }, [', how are you today']));
// hi! moss , how are you today
bind 僅是更換 this,沒有執行換資料
var user = {
name: 'leo',
sayHi: function() { return `hi! ${this.name}`; }
};
log(user.sayHi.bind({name: 'moss'})()); // hi! moss , 還要另外叫用 function 執行
僅要一行 code 就能更換 this 很方便使用呢!
但習慣用物件導向的方式處理,還是可以用在 class 身上就是了,只是這不透過 get / set 的方式,不是很習慣就是了
class User {
constructor(name) { this.name = name || 'leo'; }
sayHi() { return `hi! ${this.name}`; }
}
log( user.sayHi.call({ name: 'moss' }) ) // hi! moss ,但只要是 function 還是可行
參考 https://ithelp.ithome.com.tw/articles/10195896
參考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
留言
張貼留言