我對 JS bind、apply 和 this 有點困惑。這真的是指向視窗嗎?
function curry(fn) {
// your code here
return function curryInner(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return curryInner.bind(this, ...args); **//change this to null, still pass the test**
};
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
const curriedJoin = curry(join)
curriedJoin(1, 2, 3) // '1_2_3'
uj5u.com熱心網友回復:
不,this指向this它所在函式的背景關系。
在這種情況下,你在那里放什么并不重要,因為呼叫的唯一目的bind是創建一個已經設定了 args 的函式的副本。
return curryInner.bind(null, ...args)
基本上可以替換為
return function() {
return curryInner(args);
}
uj5u.com熱心網友回復:
這
在大多數情況下,的值this取決于函式的呼叫方式(運行時系結)。不能在執行程序中通過賦值來設定,每次呼叫函式可能都不一樣。ES5 引入了bind()設定函式 this 值的方法,而不管它是如何呼叫的,并ES2015引入了不提供自己的 this 系結的箭頭函式(它保留了
this封閉詞法背景關系的值)。它們都將 this 附加到function(或物件)中,區別在于函式呼叫(見下文)。
call將其附加到function并立即執行函式:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name " says hello " thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world");
bind 將 this 附加到函式中,它需要像這樣單獨呼叫:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name " says hello " thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world"); // output: Jim Smith says hello world"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393483.html
標籤:javascript 柯里化
