Search code examples
javascriptscopechaining

How to make inside function not go out of main function scope when doing chaining?


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 ?


Solution

  • 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/