jQuery / JavaScript“this”指针混乱 [英] jQuery/JavaScript "this" pointer confusion

查看:95
本文介绍了jQuery / JavaScript“this”指针混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用函数 bar 时,this的行为令我感到困惑。请参阅下面的代码。当从单击处理程序调用bar而不是html元素时,有没有办法安排this成为一个普通的旧js对象实例?

The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// 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);
}


推荐答案

欢迎来到javascript世界! :D

Welcome to the world of javascript! :D

你已经进入了javascript范围和关闭领域。

You have wandered into the realm of javascript scope and closure.

简而言之回答:

this.bar()

foo 的范围内执行,(因为这个指的是 foo

is executed under the scope of foo, (as this refers to foo)

var barf = this.bar;
barf();

在全球范围内执行。

this.bar基本上意味着:

this.bar basically means:

执行this.bar指向的函数,在 this (foo)的范围内。
将this.bar复制到barf时,运行barf。 Javascript理解为,运行barf指向的函数,并且由于没有 this ,它只在全局范围内运行。

execute the function pointed by this.bar, under the scope of this (foo). When you copied this.bar to barf, and run barf. Javascript understood as, run the function pointed by barf, and since there is no this, it just runs in global scope.

要纠正此问题,你可以改变

To correct this, you can change

barf();

这样的事情:

barf.apply(this);

这告诉Javascript在执行它之前将 this 的范围绑定到barf 。

This tells Javascript to bind the scope of this to barf before executing it.

对于jquery事件,您需要使用匿名函数,或者在原型中扩展bind函数以支持范围。

For jquery events, you will need to use an anonymous function, or extend the bind function in prototype to support scoping.

更多信息:

  • Good explanation on scoping
  • Extending jQuery bind to supportscoping

这篇关于jQuery / JavaScript“this”指针混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆