当调用函数栏时,“this”的行为使我困惑。请参阅下面的代码。有没有什么办法安排“这”是一个普通的老js对象实例当bar从点击处理程序,而不是作为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); }
解决方法
欢迎来到javascript世界! :D
你已经漫游到javascript范围和关闭的领域。
简短的答案:
this.bar()
在foo的范围内执行,(因为这是指foo)
var barf = this.bar; barf();
是在全局范围内执行的。
this.bar基本上意味着:
执行this.bar指向的函数,在这个(foo)的范围内。
当你复制this.bar到barf,并运行barf。 Javascript理解为,运行barf指向的函数,由于没有这个,它只在全局范围内运行。
要更正此问题,您可以更改
barf();
到这样的东西:
barf.apply(this);
这告诉Javascript在执行它之前将此范围绑定到barf。
对于jquery事件,您需要使用匿名函数,或者在原型中扩展bind函数以支持范围。
更多信息:
> Good explanation on scoping
> Extending jQuery bind to supportscoping
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。