我有一个很大的JS文件,想将其分割,比如我有这个:
page.html
<!-- some tags and jquery include... -->
<script src="example.js"></script>
<!-- externalHandlers only needs for second example, in original working example It's empty -->
<script src="externalHandlers.js"></script>
<script>
$(document).ready(function(){
var something = new Something('someValue');
);
</script>
<!-- some tags... -->
example.js
var Something = (function (document) {
"use strict";
var Something = function(x){
//initialize some stuff
};
Something.prototype.func1 = function(){
//do things
}
Something.prototype.func2 = function(){
//do things
}
//more funcs
$(document).on('click', 'a.some-class', function (e) {
//do things when click
});
$(document).on('click', 'a.some-class-2', function (e) {
//do things when click
});
return Something;
})(document);
上面的代码工作正常,但我想在另一个 js 文件中外部化点击处理程序。我试过这个:
example.js(新)
var Something = (function (document) {
"use strict";
var Something = function(x){
//initialize some stuff
};
Something.prototype.func1 = function(){
//do things
}
Something.prototype.func2 = function(){
//do things
}
//more funcs
$(document).on('click', 'a.some-class', handlerFunction);
$(document).on('click', 'a.some-class-2', function (e) {
//do things when click
});
return Something;
})(document);
externalHandlers.js
function handlerFunction(){
//do some stuff
}
但是浏览器控制台显示错误
ReferenceError: handlerFunction is not defined
TypeError: Something is not a constructor
我怎样才能做我想做的事情?这可能吗?
最佳答案
确保 externalHandlers
首先运行,以便在 example.js
运行时定义 handlerFunction
,以便 example.js
可以正确引用 handlerFunction
而不会出现错误,并且可以正确定义 Something
:
<script src="externalHandlers.js"></script>
<script src="example.js"></script>
关于javascript - 调用 javascript 处理程序的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072208/