0

I don't quite understand why the following code doesn't work. Is this some kind of restriction on the call function? The browser I'm using to run this code is Mozilla Firefox.

"use strict";

var object = {
    foo : "test",
      m : function() {
              console.log(this.foo);
          }
};

var bar = object.m.call;
bar(object); // TypeError: Function.prototype.call called on incompatible undefined

That was just an example to address a bigger, real-world issue. Consider the following:

setInterval(object.m.call, 2000, object);

I'd say, to me, this very much sounds like quite a logical way to do it, but obviously that statement is not going to work because of that TypeError.

  • You'd need to `bind` `call` to `m`. – Bergi Dec 07 '15 at 20:31
  • Chrome 46 throws 'TypeError: bar is not a function'. – Ben Aston Dec 07 '15 at 20:36
  • You're misusing `call`. What you're looking for is `var bar = object.m.bind(object);` Then, `bar();` – Steven Moseley Dec 07 '15 at 20:38
  • `Function.prototype.call` is an internal method exposed by the runtime. It expects a target. Invoking it without a target (`undefined` in this case because you are in strict mode), results in behavior peculiar to that JS engine's implementation. – Ben Aston Dec 07 '15 at 20:40
  • 1
    What you actually want is `setInterval(object.m.bind(object), 2000);`. There is no reason to use `call` at all. See also [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/1048572) – Bergi Dec 07 '15 at 21:04

0 Answers0