保留上下文的常用方法是this
什么?什么更快?你更喜欢什么?
$ .proxy(...)
$('a').on('click', $.proxy(function() {
this.close();
}, this));
Run Code Online (Sandbox Code Playgroud)var self
var self = this;
$('a').on('click', function() {
self.close();
});
Run Code Online (Sandbox Code Playgroud)让我们从修复您的代码开始。你有一个无用的函数声明,你可以使用$.proxy
as
$('a').on('click', $.proxy(this.close, this));
Run Code Online (Sandbox Code Playgroud)
现在,第二种解决方案基于self
self
变量时这可能就是它被更多使用的原因。
请注意,当您不必兼容 IE8 时,您可以使用bind:
$('a').on('click', this.close.bind(this));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
838 次 |
最近记录: |