我不知道這是不是一個愚蠢的問題,但無論如何我都會問。
我在 javascript 課程中看到,我們可以在函式上使用 bind 方法來創建基本相同但更具體的函式。例如,像這樣:
const addTax = (rate, value) => value value * rate;
null because we don't need this
const addVAT = addTax.bind(null, 0.23);
所以基本上我們在這里所做的是基于 addTax 函式創建一個名為 addVAT 的新函式,但不同之處在于我們將費率硬編碼為 0.23。
現在我的問題是:由于函式是物件并且物件是通過參考傳遞的,所以 addTax 函式現在不應該成為addVAT函式,因為它們都指向同一個參考,就像這里一樣?:
const person = {
name: 'test',
};
const person1 = person;
person1.age = 20;
因為當我們將 person1 初始化為 person 并將屬性 age 添加到 person1 時,它也會添加到 person
uj5u.com熱心網友回復:
不。
首先,您創建一個函式并將其分配給addTax
const addTax = (rate, value) => value value * rate;
然后呼叫該bind
函式的方法并將其回傳值分配給addVAT
.
const addVAT = addTax.bind(null, 0.23);
該bind
方法的目的是創建一個新函式并將其回傳。
它不僅回傳原始函式(這將毫無意義)。
的值addVAT
是由創建的新函式bind
。
uj5u.com熱心網友回復:
Bind 回傳一個新函式,并添加了一些功能。
- 修復
this
關鍵字的值 - 固定一個或多個引數的值。
const addTax = (rate, value) => value value * rate;
const addVAT = addTax.bind(null, 0.23);
const addVAT1 = addTax;
console.log(addTax === addVAT) // false
console.log(addTax === addVAT1) // true
// to understand why bind is returning new function see the polyfill of bind.
// This polyfill might not be the correct implementation but it will server the purpose
Function.prototype.myBind = function(context, ...args) {
// "this" is original function on which bind is called, addTax in your case
const fun = this;
// returned funtion when you call bind, addVAT in your case
return function(...newArgs) {
// when addVAT is called
// orignal function is executed here
return fun.apply(context, [...args, ...newArgs])
}
}
const myAddVAT = addTax.myBind(null, 0.23);
console.log(myAddVAT(2))
console.log(addVAT(2))
您可以看到 bind 從不回傳原始函式,而是回傳一個新函式,當呼叫該新函式時,將執行原始函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493470.html
標籤:javascript 功能 参考 绑定
上一篇:該用戶帳戶所有者的權限