2012-12-10 27 views
1

由于某种原因,我无法将我的设置方法中的函数调用到我的init方法中。如何将方法内部嵌套的函数调用到其他方法中

// 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') 
    } 

} 
+1

更好地解释你想做 – Alexander

+0

设置在它前面有一个下划线...'this._settings()' – Shmiddty

+0

对不起,那只是一个排字错误 – user759235

回答

1

这可能是你的意思:

Plugin.prototype = { 

    settings: function(){ 

    }, 

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

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

}; 

或者,如果你想让你好()私有的,你可以这样做:

Plugin.prototype = function(){ 

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

    return { 
     settings: function(){ 
     }, 

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

jsfiddle

+0

谢谢,这可以帮助我! – user759235

4

Javascript has function scope。如果你在另一个函数中声明一个函数,它只在外部函数中可见。

+0

同意。请参阅[这个SO问题](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)关于闭包。 – jaudette

+0

啊我认为一个功能可以在范围之外使用....傻我,我怎样才能使用范围外的功能 – user759235

+0

是的,我认为我必须将它移动到主范围... – user759235

相关问题