I got a little confused with JS bind, apply, and this. Does this here actually point to the window?
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'
CodePudding user response:
No, this
points to the this
context of the function it is in.
In this case, it really doesn't matter what you put there since the only purpose of calling bind
is to create a copy of the function with the args already set.
return curryInner.bind(null, ...args)
could essentially be replaced with
return function() {
return curryInner(args);
}
CodePudding user response:
this
In most cases, the value of this
is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind()
method to set the value of a function's this regardless of how it's called, and ES2015
introduced arrow functions which don't provide their own this binding (it retains the
this
value of the enclosing lexical context).
They all attach this into function
(or object) and the difference is in the function invocation (see below).
call
attaches this into function
and executes the function immediately:
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 attaches this into function and it needs to be invoked separately like 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"