Given the following how do i enable this to work correct?
return {
methodA: function() {
return methodB();
},
methodB: function() {
alert("hi");
}
}
You need to reference the context, via this.
var foo = {
methodA: function() {
return this.methodB(); //context
},
methodB: function() {
alert("hi");
}
}
foo.methodA(); //alerts "hi"
foo.methodA(), just a warning so the OP knows to avoid doing var func = foo.methodA and calls func(). See my answer for a safer alternative.It seems you are returning from a module like function. The safe way is not to use this, it is to keep a reference to the object so that it won't matter how the function is called.
function getObj() {
var obj = {
methodA: function() {
return obj.methodB();
},
methodB: function() {
alert("hi");
}
};
return obj;
}
var myObj = getObj();
// Works
myObj.methodA();
// Works but would not work if you were using `this` as suggested by Utkanos.
someDomElement.addEventListener('click', myObj.methodA);
return this.methodB();