I’ve just been restructuring my code into objects and using the this keyword, I’ve got this problem whereby, setting the prop works, but then when the second method fires, myProp is undefined. I’ve noticed if I use myObj to set and get rather than this it works fine. What’s the difference here? What am I doing wrong? I though this was referring to the instance of which there is only one which was automatically instantiated by the object literal.
var myObj = {
SetProp: function (id) {
this.myProp = "abc";
Ajax.GetJSONAfterStandardLogic(Utility.PrefixURL("/ajax/mymethod"), this.SetPropSuccess);
},
SetPropSuccess: function (response) {
console.log("test " + this.myProp);
}
}
Likely because when you call those functions,
thisis not the object.thisis the binding with which the function was called.A bit more code to demonstrate how you’re calling the function would be useful, but you can make it work by using:
This binds myObj as
this, for the SetProp function call.If you put
console.log(this)in either of those functions, you’ll probably find thatthisis not what you’re expecting.