Example:
function testFunc() {
this.insideFunc = function(msg) {
alert(msg);
}
return this;
}
testFunc().insideFunc("Hi!");
insideFunc("Hi again!");
Why the inside function is visible in global scope, how to prevent that ?
That's because this is window.
To use this in this manner, you'd have to use:
var _testFunc = new testFunc();
Building on ethagnawl's answer, you can use this trick to force your function to new itself if the caller forgets:
function testFunc() {
// if the caller forgot their new keyword, do it for them
if (!(this instanceof testFunc)) {
return new testFunc();
}
this.insideFunc = function(msg) {
alert(msg);
}
return this;
}
http://jsfiddle.net/qd7cW/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With