代码之家  ›  专栏  ›  技术社区  ›  I. J. Kennedy ShankarSangoli

jQuery/JavaScript“this”指针混淆

  •  25
  • I. J. Kennedy ShankarSangoli  · 技术社区  · 16 年前

    “this”在执行函数时的行为 bar 这叫我困惑。请参阅下面的代码。当从单击处理程序调用bar时,有没有办法将“this”安排为普通的旧js对象实例,而不是html元素?

    // a class with a method
    
    function foo() {
    
        this.bar();  // when called here, "this" is the foo instance
    
        var barf = this.bar;
        barf();   // when called here, "this" is the global object
    
        // when called from a click, "this" is the html element
        $("#thing").after($("<div>click me</div>").click(barf));
    }
    
    foo.prototype.bar = function() {
        alert(this);
    }
    
    7 回复  |  直到 15 年前
        1
  •  36
  •   codechurn    10 年前

    欢迎来到javascript世界D

    您已经进入了javascript作用域和闭包的领域。

    this.bar()
    

    在以下范围内执行: ,(作为

    var barf = this.bar;
    barf();
    

    在全局范围下执行。

    这个.bar基本上意味着:

    在的范围内执行this.bar所指的函数 (foo)。 将此.bar复制到barf并运行barf时。Javascript理解为,运行barf所指的函数,因为没有

    要更正此问题,您可以更改

    barf();
    

    barf.apply(this);
    

    这告诉Javascript绑定 在执行之前呕吐。

    有关更多信息:

        2
  •  5
  •   Pawel Krakowiak    16 年前

    这是一个很好的解释 this QuirksMode

        4
  •  2
  •   Chris Brandsma    16 年前

    获取这本书:JavaScript:好的部分。

    此外,尽可能多地阅读道格拉斯·克罗克福德的著作 http://www.crockford.com/javascript/

        5
  •  2
  •   moff    16 年前

    你可以用 Function.apply 关于函数设置什么 this

    $("#thing").after($("<div>click me</div>").click(function() {
        barf.apply(document); // now this refers to the document
    });
    
        6
  •  1
  •   Martin    16 年前

    这是因为

    您可以通过以下匿名功能帮助自己:

    function foo() {
      var obj = this;
      $("#thing").after($("<div>click me</div>").click(function(){obj.bar();}));
    }
    
    foo.prototype.bar = function() {
      alert(this);
    }
    
        7
  •  0
  •   Boki    11 年前
    this.bar();  // when called here, "this" is the foo instance
    

    在这里:

    foo();//this stands for window