Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 902
rsk82 Avatar asked Jan 30 '26 07:01

rsk82


2 Answers

That's because this is window.

To use this in this manner, you'd have to use:

var _testFunc = new testFunc();
like image 149
pdoherty926 Avatar answered Feb 01 '26 23:02

pdoherty926


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/

like image 24
jbabey Avatar answered Feb 01 '26 21:02

jbabey