使用实例方法作为事件处理程序的回调将范围this从 “我的实例” 更改为 “无论什么叫回调” 。所以我的代码看起来像这样
this
function MyObject() { this.doSomething = function() { ... } var self = this $('#foobar').bind('click', function(){ self.doSomethng() // this.doSomething() would not work here }) }
它有效,但这是最好的方法吗?我觉得很奇怪
这个问题并非特定于jQuery,而是通常特定于JavaScript。核心问题是如何在嵌入式函数中“引导”变量。这是示例:
var abc = 1; // we want to use this variable in embedded functions function xyz(){ console.log(abc); // it is available here! function qwe(){ console.log(abc); // it is available here too! } ... };
此技术依赖于使用闭包。但这不能使用,this因为它this是一个伪变量,可能会随着范围的变化而动态变化:
// we want to use "this" variable in embedded functions function xyz(){ // "this" is different here! console.log(this); // not what we wanted! function qwe(){ // "this" is different here too! console.log(this); // not what we wanted! } ... };
我们能做什么?将其分配给某个变量,并通过别名使用它:
var abc = this; // we want to use this variable in embedded functions function xyz(){ // "this" is different here! --- but we don't care! console.log(abc); // now it is the right object! function qwe(){ // "this" is different here too! --- but we don't care! console.log(abc); // it is the right object here too! } ... };
this在这方面不是唯一的:arguments是另一个应以相同方式处理的伪变量-通过别名。
arguments