var Dog = function() {
var _instance = 'hello world';
return function() {
console.log(this._instance);
}
} (); //note that it is self invoking function
var l = new Dog(); //#> undefined
In the above case I was expecting an output of:
‘hello world’
Why is this._instance not accessing the the variable which should be accessible by virtue of closure? I tested this in FF and am getting undefined.
You don’t assign
_instanceto the object, it’s just a closure variable, and should be accessed without usingthis:I’d probably write it like so instead:
Note that I have not tried to compile the above code, so it might contain a few mistakes. Nothing JsLint can’t handle though!
You might want to consider adding filtering to the
setOptionsmethod so that it doesn’t assign properties you don’t want, or filter out methods etc declared in the options-parameter.Additionally, if you use JQuery, or similar library, there are (often) utility functions for merging objects, making it trivial to write the setOptions-method: