For some time now, I've been using the design pattern of objectOne, shown below. I cannot remember where I picked it up. I tried to find it but couldn't. Perhaps its some hybrid of things I read about. Today I discovered that it is very flawed, since this is resolving to the window object, making all public methods global. I was under the impression that when this is used within a function, it would refer to the function itself, as opposed to the global window object. I guess this is not the case? Could someone explain something that I'm missing or point me to a resource that explains it? I'm also interested in either fixing this pattern or finding a similar one that doesn't have this problem with global method names. I suppose if I would use a variable other than this, perhaps fn, and i return that, then it would fix things. Thanks in advance for any help with this question, sorry its sort of vague.
JS Fiddle: http://jsfiddle.net/nLL8y/3/
myapp = {};
myapp.objectOne = function() {
var that = this,
p = {};
this.public = function() {
console.log(this);
};
p.private = function() {};
return this;
}();
myapp.objectTwo = {
public: function() {
console.log(this);
},
notPrivate: function() {}
};
myapp.objectThree = function() {
var fn = {},
p = {};
fn.public = function() {
console.log(this);
};
p.private = function() {};
return fn;
}();
//creates global functions
myapp.objectOne.public();
//doesn't allow private
myapp.objectTwo.public();
//seems to work
myapp.objectThree.public();
thisnever refers to the function itself, unless you explicitly set it:func.call(func).thisin objectOne would behave as it does in objectTwo and refer to the parent object instead of the window. I guess I'm missing something about function scopes andthis. I'll have to read more about it, but I thought I was using a common design pattern but apparently I was way off base. I usedthissince I thought its a convention