【问题标题】:jquery couldn't access property inside of object [duplicate]jquery无法访问对象内部的属性[重复]
【发布时间】:2016-09-19 15:32:27
【问题描述】:
function foo(){
    var a = 1;
    this.b = 2;

    this.c = function(){
        alert(a);
        alert(this.b);

        $('.ei').each(function(){
            alert(a);
            alert(this.b);//undefined <-- i need this to be update to 3
        });
    }

}

var obj = new foo;
obj.b = 3; //update this property before call method
obj.c();

我有一个包含 jquery each() 的方法,我尝试访问该对象的属性,但我得到未定义

我需要这个属性能够更新

有人知道怎么做吗?

【问题讨论】:

  • this inside each 将引用集合中的当前元素。将this 缓存到that 并使用that.b

标签: javascript jquery oop


【解决方案1】:

您需要将其绑定到函数。

this.c = function(){
    alert(a);
    alert(this.b);

    $('.ei').each(function(){
        alert(a);
        alert(this.b);//undefined <-- i need this to be update to 3
    }.bind(this));
}.bind(this);

【讨论】:

  • 我只是尝试,它不起作用,你错过了每个()末尾的“)”;
  • 是的,你需要 .bind(this) 来分配给 this.c 的函数,它应该可以工作。我编辑了帖子,请立即查看。
  • 如果你的词法范围内有你需要的变量,那么真的没有必要使用.bind - 它比你自己为副本起别名效率低
  • 外层this.c上的.bind也是完全没必要的
猜你喜欢
  • 2012-09-29
  • 2011-11-05
  • 2022-01-16
  • 1970-01-01
  • 2020-01-20
  • 2019-10-29
  • 2012-08-03
  • 1970-01-01
  • 2019-02-04
相关资源
最近更新 更多