简体   繁体   English

结合使用bind(this)和jQuery.each,模糊地使用“ this”

[英]Using bind(this) together with jQuery.each, ambiguous use of “this”

I've got a complex JS app, OOP style, where objects hirearchy is used. 我有一个OOP风格的复杂JS应用程序,其中使用了对象层次结构。 Class Grandfather is extended by class Father, which is extended by class Child. 祖父级由父亲级扩展,父级由子级扩展。 I've got different instances of class Child. 我有Child类的不同实例。

To avoid property confusion and mix-up, I am heavily using .bind(this) to callback. 为避免属性混淆和混淆,我大量使用.bind(this)进行回调。 Example

$(this.buttonId).click(function(evt)) {
    console.log(this.myProperty);
    this.myMethod();
}.bind(this));

In this way I am sure that this.myProperty and this.myMethod are always "mine", and not my father's or my brother's. 通过这种方式,我可以确保this.myProperty和this.myMethod始终是“我的”,而不是父亲或兄弟的。

Now i need to rely on jQuery.each method . 现在我需要依靠jQuery.each方法 But to access each item I need "this" again! 但是要访问每个项目,我需要再次“ this”!

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

So, if I bind the callback to "this" (object), it's going to become: 因此,如果将回调绑定到“ this”(对象),它将变成:

$( "li" ).each(function( index ) {
    console.log( index + ": " + $( this ).text() );
    console.log(this.myProperty);
    this.myMethod();
}.bind(this));

causing an ambiguous use of "this" which, of course, leads to lots of errors. 导致“ this”的模棱两可使用,这当然会导致很多错误。

Any ideas? 有任何想法吗? Thank you 谢谢

Set a local variable before jquery-each function: 在jquery-each函数之前设置局部变量:

var me = this;
$( "li" ).each(function( index ) {
    console.log( index + ": " + $( this ).text() );
console.log(me.myProperty);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM