javascript object oriented function invoke beginner question
-
11-09-2019 - |
Question
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' ????
};
}
Solution
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 this
is not required in this.function_two
:
// Inside the MyObject constructor:
function function_one(param) {
return param + param;
}
// Optional, if you don't care about being able to call
// function_one from outside the closure
this.function_one = function_one;
This makes it so that function_one
is 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.
OTHER TIPS
Yes, unlike Java/C#/C++ you must specify this