Javascript 如何将嵌套在方法中的函数调用到其他方法中
由于某些原因,我无法将settings方法中的函数调用到init方法中Javascript 如何将嵌套在方法中的函数调用到其他方法中,javascript,methods,Javascript,Methods,由于某些原因,我无法将settings方法中的函数调用到init方法中 // this is how I use it now(dont work) Plugin.prototype = { settings: function(){ function hello(name){ alert('hi, '+name) } }, init: function(){ this.setting
// 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')
}
}
Javascript具有函数作用域。如果您在另一个函数中声明一个函数,则它仅在外部函数中可见。Javascript具有函数作用域。如果您在另一个函数中声明一个函数,则它仅在外部函数中可见。这可能就是您的意思:
Plugin.prototype = {
settings: function(){
},
hello: function(name){
alert('hi, '+name);
},
init: function(){
this.settings();
this.hello('John Doe');
}
};
或者,如果要将hello()设为私有,可以执行以下操作:
Plugin.prototype = function(){
var hello = function (name){
alert('hi, '+name);
};
return {
settings: function(){
},
init: function(){
this.settings();
hello('John Doe');
}
};
}();
这可能就是你的意思:
Plugin.prototype = {
settings: function(){
},
hello: function(name){
alert('hi, '+name);
},
init: function(){
this.settings();
this.hello('John Doe');
}
};
或者,如果要将hello()设为私有,可以执行以下操作:
Plugin.prototype = function(){
var hello = function (name){
alert('hi, '+name);
};
return {
settings: function(){
},
init: function(){
this.settings();
hello('John Doe');
}
};
}();
同意。看看闭包。啊,我以为一个函数可以在作用域之外使用……愚蠢的我,我怎么能在作用域之外使用函数呢scope@user759235您不必移动它……您可以让
settings()
返回它(以具有多个方法的对象文本的形式)。这取决于设置
除了您提供的代码之外的所有功能好的,但我不知道这一点,所以我知道这与调用()有关。同意。看看闭包。啊,我以为一个函数可以在作用域之外使用……愚蠢的我,我怎么能在作用域之外使用函数呢scope@user759235您不必移动它……您可以让settings()
返回它(以具有多个方法的对象文本的形式)。这取决于settings
除了您提供的代码之外的所有功能,好吧,但我在这方面不在行,所以我知道这与调用()有关?最好解释一下您想要做什么设置前面有一个下划线<代码>这个。_settings()最好解释一下你想要做什么。设置前面有下划线<代码>此。\u设置()