Benjamin W Benjamin W - 2 months ago 6
Javascript Question

jquery couldn't access property inside of object

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();


I have a method contain jquery each(), and I try to access this object's property, but i get undefined

I will need this property able to update

anyone know how to make this work?

Answer

You need to bind this to function.

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);