I’m trying to wrap my head around building a custom JavaScript library. I’ve read a lot about the module pattern, and also read Crockford’s articles on private and public members. I know what is an immediately invoked function expression and why we do stuff like
var myLib = (function() {
}())
However, I’m still a little lost in some cases regarding scope and closures in general. The concrete problem I have is:
Why does the following example alert DOMWindow, rather than the myLib object?
http://jsfiddle.net/slavo/xNJtW/1/
It would be great if you can explain what “this” refers to in all of the methods in that example and why.
Inside any function declared (anywhere) and invoked as follows
thiswill be window objectIf you want to create private functions and access the instance of ‘myObject’ you can follow either of the following methods
One
Two
These are solutions to your issue. I would recommend using prototype based objects.
EDIT:
You can use the first method.
In fact here
myObjectis in the same scope asprivateFuncand you can directly use it inside the functionThe real scenario were you can use a proxy for
thisis shown below. You can usecallalso.