jQuery/JavaScript"这个"指针混乱

I. *_*edy 25 javascript jquery this

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

// 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);
}
Run Code Online (Sandbox Code Playgroud)

Aar*_*ian 35

欢迎来到javascript世界!:d

你已经徘徊在javascript范围和闭包领域.

简而言之:

this.bar()
Run Code Online (Sandbox Code Playgroud)

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

var barf = this.bar;
barf();
Run Code Online (Sandbox Code Playgroud)

在全球范围内执行.

this.bar基本上意味着:

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

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

barf();
Run Code Online (Sandbox Code Playgroud)

这样的事情:

barf.apply(this);
Run Code Online (Sandbox Code Playgroud)

这让JavaScript的范围绑定执行前BARF.

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

欲了解更多信息:

  • 我自己并不是100%肯定术语,但我认为这个答案(以及与之相关的资源)使"范围"与"执行上下文"混淆.`this`指向的对象是*执行上下文*,完全独立于*scope*(闭包与此有关).范围是在函数的创建时确定的,并确定函数可以看到的变量; 每当调用函数时确定执行上下文,并确定"this"引用的内容.在这里将'范围'替换为"执行上下文",只有这样才会正确 - 我想! (2认同)

Paw*_*iak 5

QuirksModethis提供的JavaScript关键字有很好的解释.