i got a question when create a javascript object,
when one function invoking another function within the object, do we need to use ‘this’
MyObject = function() {
this.function_one = function(param) {
return param + param;
};
this.function_two = function(param) {
return this.function_one(param) * this.function_one(param);
// when invoking function_one, do i need to use 'this' ????
};
}
In this situation, yes. This is because you assign the anonymous function to be a property of the newly constructed object, which is the only way to access it.
It is possible to make it so that
thisis not required inthis.function_two:This makes it so that
function_oneis available as a variable inside the closure created by calling the constructor; making functions available to call two different ways (via free variable and object property) isn’t a very common idiom, though.I suggest you read this article by Crockford for a better understanding of the different ways you can attach methods to objects.