2

如果我有 :

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

如何使它工作?:

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

1 回答 1

3

a用调用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";

演示:http: //jsbin.com/uferif/

于 2012-07-05T13:38:43.643 回答