--- tags: Javascript, disqus: hackmd --- # [JS]call、apply、bind [[筆記] 了解function borrowing和function currying ─ bind(), call(), apply() 的應用](https://pjchender.blogspot.com/2016/06/function-borrowingfunction-currying.html) [JavaScript - call,apply,bind](https://ithelp.ithome.com.tw/articles/10195896) [Javascript的this](https://hackmd.io/rrwJQdqxSCyJzrrXPbQlYg?view) [Javascript的this|chrisHsiao](https://hackmd.io/rrwJQdqxSCyJzrrXPbQlYg?view) [作用域 (Scope)](https://hackmd.io/zbZx_kfNTQq1jRUA_03QUA?view) --- 更改 this 的值的方法有三種。 > call、apply、bind 而call跟apply這兩種非常相似 ```javascript= '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 ``` --- ```java= var person = { firstName: 'Jeremy', lastName: 'Lin', getFullName: function() { var fullName = this.firstName + ' ' + this.lastName; return fullName; } } var logName = function(location1, location2) { console.log('this', this); console.log('Logged: ' + this.getFullName()); } logName(); //this.getFullName is not a function ``` logName()會報錯的原因很簡單,就是logName這個函式的this指向的是window。 如果不知道為什麼,可以先看這篇[Javascript的this](https://hackmd.io/rrwJQdqxSCyJzrrXPbQlYg?view)。 ### 使用bind ```javascript= var aaa = logName.bind(person); aaa(); ``` 將person這個物件帶入,如此一來在logName裡的this就變成指向person這個物件。 如果logName需要帶入參數要怎麼寫,可以把bind綁到函式後面。 因為只要在JavaScript中建立的函式,都會預設有bind這個方法在內。 ```javascript= var person = { firstName: 'Jeremy', lastName: 'Lin', getFullName: function() { var fullName = this.firstName + ' ' + this.lastName; return fullName; } } var logName = function(location1, location2) { console.log('this', this); console.log('Logged: ' + this.getFullName()); console.log('地點: ' + location1 + ' ' + location2); }.bind(person); var aaa = logName('Taiwan', 'Taichung'); aaa(); ``` ### 使用call call的用法其實就和括號 ( ) 一樣,都是直接去執行(invoke)這個函式,但是不一樣的地方在於,call的後面可以帶入你想要指定this的物件,接著再放入參數,`fun.call(thisArg[, arg1[, arg2[, ...]]])`。 ```javascript= logName.call(person, 'Taiwan', 'Taichung'); ``` ### 使用apply apply和call的用法大同小異,唯一不同的地方在於,使用apply時,放入參數的地方,要放入的是陣列(array)。 ```javascript= logName.call(person, ['Taiwan', 'Taichung']); ```