I see a lot that function returns NOT the result but the function.
The example below shows that function getWindow returns function. Why it can’t just return variable “win”? When I return result and when function?
Thank you.
var A = function(){};
A.prototype=
{
getWindow : function()
{
var win = new B.window();
return (
this.getWindow = function()
{
return win;
})();
}
}
This code is equivalent to your code but is easier to understand:
Usage:
First, create an A instance:
Then, call
getWindowon that instance:Here, the
getWindowmethod ofA.prototypeis called. As you can see in my code above,A.prototype.getWindowwill create anew B.window()and return it, however in between, it will also create agetWindowmethod on the instance object itself.Now, if you call
getWindowagain:A.prototype.getWindowis no longer called because the instance object itself has agetWindowmethod. This method returns the same “win” object that was returned when thegetWindowmethod was called for the first time.Your pattern allows for multiple
Ainstances to use the sameA.prototype.getWindowmethod to instantiate their own “win” objects. Consider this:This is quite a useful pattern
:)Update:
This is your code:
First, let’s take a look at the expression inside the parens:
As you can see, it’s an assignment expression. An anonymous function object is assigned to the
getWindowproperty of the object referenced bythis(the instance object).Note that this function returns the
winobject.The result of this assignment expression is the function object itself! This means that the value inside the parens is the function object.
Now, let’s take a look at the whole picture:
We can remove the parens since we don’t need them anymore:
As you can see, the function object is called, and then the return value of that function is returned.
As mentioned above, the function returns
win. Therefore, the code resolves to this:So what your code does is:
FIRST, it assigns
function() { return win; }tothis.getWindow.SECOND, it returns the result of calling that function which is
win.My code produces the same result but is easier to understand: