0

I have a function which is called with a callback. I need to call() this callback with the "this" argument, but it doesn't work !

I have try to call a private function, and it works, but it doesn't work with the cb...

function foo(cb) {
    this.test = "IT WORKS"
    cb.call(this);
}

foo(() => {
    console.log(this);
});

The result expected in the console should be {text: "IT WORKS"} but the actual output is the Window object.

The question is also: Why i can not call() a callback with this

Théotime
  • 17
  • 5
  • 1
    When you call `foo()` the way you're calling it, `this` will be set to the global object (or `undefined` in "strict" mode). On top of that, you're using an `=>` function for your callback, and `=>` functions do not have their own `this`. – Pointy Aug 27 '19 at 13:54
  • if I don't use a `=>` function, but `function() {}` it doesn't work yet... – Théotime Aug 27 '19 at 13:56
  • `this` only makes sense when creating instances, aka `new Object`.. – Keith Aug 27 '19 at 13:56
  • I have reproduced an example, but else I use instances. – Théotime Aug 27 '19 at 13:57
  • The only `this` in your current code is the window object, and that's only because your not running the code in strict mode. It might be better, if you try and explain what your trying to do. – Keith Aug 27 '19 at 14:01
  • here it works, sorry... https://jsfiddle.net/bwx87c29/ – Théotime Aug 27 '19 at 14:12

0 Answers0