Javascript 访问不在范围内的函数
我有下面的javascript代码:Javascript 访问不在范围内的函数,javascript,jquery,function,scope,Javascript,Jquery,Function,Scope,我有下面的javascript代码: (function($){ function JsBarcode(){ //Some Code Here } })(window.jQuery); (function ($) { JsBarcode(); //calls a JsBarcode not within a scope })(jQuery); 运行上述代码时,会出现以下错误: Uncaught ReferenceError: JsBar
(function($){
function JsBarcode(){
//Some Code Here
}
})(window.jQuery);
(function ($) {
JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);
运行上述代码时,会出现以下错误:
Uncaught ReferenceError: JsBarcode is not defined
我正在尝试调用一个不在范围内的函数。如何调用它?这是因为
JsBarcode
是在匿名函数中声明的,因此它只能在声明它的匿名函数的有限范围内使用
一种可能的解决方案是将声明移到匿名函数之外
另一种方法是使用全局变量存储对函数的引用,如下所示
//declare it as a gloal variable
var JsBarcode;
(function ($) {
//assign the value of JsBarcode as the function
JsBarcode = function () {
//Some Code Here
}
})(window.jQuery);
(function ($) {
JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);
这是因为
JsBarcode
是在匿名函数中声明的,因此它仅在声明它的匿名函数的有限范围内可用
一种可能的解决方案是将声明移到匿名函数之外
另一种方法是使用全局变量存储对函数的引用,如下所示
//declare it as a gloal variable
var JsBarcode;
(function ($) {
//assign the value of JsBarcode as the function
JsBarcode = function () {
//Some Code Here
}
})(window.jQuery);
(function ($) {
JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);
2种选择:
-您可以更改结构,使第二个模块位于第一个:父范围始终可见。
-您可以更改导出函数的第一个模块,以便可以在外部访问它。下面的示例
var firstModuleHandle=(函数($){
var JsBarcode=函数(){
//这里有一些代码
日志(“可以访问我吗?”);
}
返回{JsBarcode:JsBarcode};
})(window.jQuery);
(函数($){
JsBarcode();
//调用不在范围内的JsBarcode
})(jQuery)代码>
2选项:
-您可以更改结构,使第二个模块位于第一个:父范围始终可见。
-您可以更改导出函数的第一个模块,以便可以在外部访问它。下面的示例
var firstModuleHandle=(函数($){
var JsBarcode=函数(){
//这里有一些代码
日志(“可以访问我吗?”);
}
返回{JsBarcode:JsBarcode};
})(window.jQuery);
(函数($){
JsBarcode();
//调用不在范围内的JsBarcode
})(jQuery)代码>
如果您不想混乱全局名称空间,也可以将其作为jQuery的属性。。。迷你插件
(function($){
// assign to $ namespace
$.JsBarcode = function (){
//Some Code Here
}
})(window.jQuery);
(function ($) {
// call jQuery.JsBarcode()
$.JsBarcode();
})(jQuery);
如果您不想混乱全局名称空间,也可以将其作为jQuery的属性。。。迷你插件
(function($){
// assign to $ namespace
$.JsBarcode = function (){
//Some Code Here
}
})(window.jQuery);
(function ($) {
// call jQuery.JsBarcode()
$.JsBarcode();
})(jQuery);
答案很简单……不进行重组就无法实现,所以它在范围之内。可以创建一个全局对象变量并指定该对象的一个属性来引用functionanswer非常简单…如果不重新构造,则无法实现,因此它在范围内。可以创建全局对象变量并指定该对象的属性以引用函数