John
John

Reputation: 7910

add new function to object

If I have :

  function myFunc(a)
  {
    if(! (this instanceof myFunc) ) return new myFunc(a);
    this.myVar = "FOOBAR";
  }

How to make this to work? :

  myFunc(function() { alert(this.myVar )}); // output must be "FOOBAR";

Upvotes: 2

Views: 85

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47127

Call a with this.

  function myFunc(a)
  {
    if(! (this instanceof myFunc) ) return new myFunc(a);
    this.var = "FOOBAR";

    a.call(this); // <-- Added this line
  }

  myFunc(function() { alert(this.var)}); // output must be "FOOBAR";

DEMO: http://jsbin.com/uferif/

Upvotes: 3

Related Questions