I am trying to create an object with multiple methods, but I want some methods to use other methods from the same object. Here is an example:
var myObj = {
sum: function (a,b) {
return a + b;
},
somethingThatUsesSum: function (a,b) {
return this.sum(a,b) * 5;
}
};
This "works" if you call it as follows:
myObj.somethingThatUsesSum(1, 2);
because this
is set to myObj
. However, if you use apply, it doesn't work unless you explicitly set this
to be myObj
.
I don't like using this
in somethingThatUsesSum
, but I'm wondering if there is a better way.
I know I could create a closure with a local function sum
that can be used by both functions in myObj
, but I wanted to know if there was another way closer to the approach proposed above.