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函数以支持范围.
欲了解更多信息:
| 归档时间: |
|
| 查看次数: |
19168 次 |
| 最近记录: |