1.2.3.21.call()、apply() 與 bind()
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
1.變數環境 (Variable environment), 外部環境 (Outer environment)
當在變數環境找不到變數時, 會到所參照的外部環境去尋找
2.this
不須宣告, 由JavaScript engine產生, this依據函數的呼叫方式會指向不同的物件
3.外部參照的環境
函數除了CODE property與name property外, 預設會有call(), apply(), bind()
function currying
建立一個函數的拷貝並設定預設的參數
bind: 將this重新指向, 創造函數的拷貝並返回但不會執行
call: 將this重新指向並傳入其他參數, 並執行函數
apply: 將this重新指向並傳入其他參數, 並執行函數
//程式碼1
var person = {
firstname = 'John',
lastname = 'Doe',
getFullFunction: function (){
var fullname = this.firstname + ' ' + this.lastname;
return fullname;
}
}
//程式碼2
var logName = function(lang1, lang2){
console.log('Logged: ' + this.getFullName())
}
//執行失敗
logName();
//程式碼3
var logPersonName = logName.bind(person)
logPersonName();
//程式碼4
var logName = function(lang1, lang2){
console.log('Logged: ' + this.getFullName())
}.bind(person)
logName();
//程式碼5
var logName = function(lang1, lang2){
console.log('Logged: ' + this.getFullName())
}
logName.call(person, 'en', 'es');
//程式碼6
logName.apply(person, ['en', 'es']);
//程式碼7
(function(lang1, lang2){
console.log('Logged: ' + this.getFullName())
}).apply(person, ['en', 'es']);
//function borrowing
var person2 = {
firstname = 'Jane',
lastname = 'Doe'
}
console.log(person.getFullName.apply(person2));
//function currying
function multiply(a, b) {
return a * b;
}
var multiplyByTwo = multiply(this, 2);
//印出8
console.log(multiplyByTwo(4));