0

I'm learning about "bind", and I found there is another way of using the wrap function, without using "bind". I can code like below.

let user = {
  firstName: "John",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};


//using wrap function instead of bind 
setTimeout(function() {
  user.sayHi(); // Hello, John!
}, 1000);

If you use setTimeout(user.sayHi, 1000); instead of wrap function, it doen't work. I know why. But I can't understand, why does it work when you use wrap function?

aya2222
  • 1
  • 2
  • As a rule of thumb the value of `this` is whatever is before the last `.` when you call the function. When you have `a.b.c()` then `this = `a.b`. When you have `a.b()` then `this = a`. When you have `a()` then you have `this = undefined` (substituted for the global object in non-strict mode). A function using a callback would normally just do `function fn(callback) { callback() }` so if you do `fn(a.b.c)` what actually gets called is the function but with nothing before the last dot. So, you transform it from `a.b.c()` form to `a()` form losing the context. – VLAZ May 26 '21 at 21:04
  • You can do `setTimeout(user.sayHi.bind(user), 1000)`. – connexo May 26 '21 at 21:16

0 Answers0