1

For some reason I cant call a function thats inside my settings method into my init method.

    // this is how I use it now(dont work)

Plugin.prototype = {

    settings: function(){

        function hello(name){
            alert('hi, '+name)
        }
    },

    init: function(){
        this.settings() 
        hello('John Doe')
    }

}
user759235
  • 2,147
  • 3
  • 39
  • 77

2 Answers2

4

Javascript has function scope. If you declare a function within another function, it's only visible inside the outer function.

jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • Agree. See [this SO question](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) about closures. – jaudette Dec 10 '12 at 23:43
  • Ah I thought that a function could be used outside a scope....silly me, how can I use a funtion outside a scope – user759235 Dec 10 '12 at 23:44
  • @user759235 You don't _have_ to move it...you could have `settings()` return it (in the form of an object literal that has multiple methods). It depends on all what `settings` does other than your code you provided – Ian Dec 10 '12 at 23:48
  • Okay but I am a noob at this so I know it has something to do with the call()? – user759235 Dec 11 '12 at 00:00
1

This may be what you meant:

Plugin.prototype = {

    settings: function(){

    },

    hello: function(name){
        alert('hi, '+name);
    },

    init: function(){
        this.settings();
        this.hello('John Doe');
    }

};

Or, if you wanted to make hello() private, you could do this:

Plugin.prototype = function(){

  var hello = function (name){
      alert('hi, '+name);
  };   

  return {
      settings: function(){
      },

      init: function(){
          this.settings();
          hello('John Doe');
      }
  };
}();

jsfiddle

saille
  • 9,014
  • 5
  • 45
  • 57