我理解這是如何作業的,但不明白為什么我們要使用 apply 和“this”關鍵字,如下例所示:
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
} else {
return curried.bind(this, ...args)
}
}
}
這里 bind 和 apply 使用“this”作為第一個引數,但是如果我們可以只做 func(args) 的目的是什么,因為 this 指向一個函式的相同詞法環境。我可以通過箭頭函式看到它的一些好處,但在這里我命名了函式。沒有區別還是我錯過了什么?
uj5u.com熱心網友回復:
使用的原因apply是保持 的值不變this。呼叫func(args)將導致this成為window物件(在非嚴格模式下)或undefined(在嚴格模式下)。
這是一個如果您呼叫會中斷的示例func(args):
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func(args);
} else {
return curried.bind(this, ...args);
}
};
}
const example = {
multiplier: 5,
calculate: function (a, b) {
return (a b) * this.multiplier;
},
};
example.curriedVersion = curry(example.calculate);
// Because of the way these are being called, `this` should be `example`
console.log(example.calculate(1, 2));
// But here it's not, causing unexpected results
console.log(example.curriedVersion(1)(2));
但如果你這樣做,它會起作用apply(this, args):
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return curried.bind(this, ...args);
}
};
}
const example = {
multiplier: 5,
calculate: function (a, b) {
return (a b) * this.multiplier;
},
};
example.curriedVersion = curry(example.calculate);
// Because of the way these are being called, `this` should be `example`
console.log(example.calculate(1, 2));
console.log(example.curriedVersion(1)(2));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419451.html
標籤:
