Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object´s Attribute forgets value

Tags:

javascript

I´m not very experienced with JavaScript.

I defined an Object with an attribute. A method of the object makes a jQuery post with another method of the object as callback. In this second method the attribute has forgotten its value, alert prints 'undefined'

var myObj=
{ attr1 : 'val1',

  method1 : function()
    { $.post("__AX_getContent?edit=true").done(this.method2);
      alert(this.attr1);
    },

    method2: function(data)
    { alert(this.attr1);
    }
}

$(myObj.method1());

what am I doing wrong to have the attributes value in method2?

like image 469
mica Avatar asked Jul 01 '26 18:07

mica


1 Answers

That is because this in the second method is a XHR object send by AJAX.

Try using the .bind function prototype.

$.post("__AX_getContent?edit=true").done(this.method2.bind(this));
like image 178
Karl-André Gagnon Avatar answered Jul 03 '26 07:07

Karl-André Gagnon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!