我的问题简而言之:我在一个 js 文件(文件名:generation.js)中创建了一个对象构造函数,我想在另一个 js 文件中使用该构造函数创建一个对象(文件名:timeline.js)。当我尝试这样做时,我收到错误消息:Uncaught ReferenceError: generation (the object I want to create) is not defined.
在 HTML 中,我有正确顺序的 js 文件:首先是 generation.js,然后是 timeline.js。我还有 jQuery 行。 如果我尝试在对象定义所在的同一文件(在 generation.js 中)中使用构造函数,它会正常工作。然后我将该代码复制到新文件中,但它不再起作用了。
代码:
Generation.JS:
这是我定义对象构造函数的地方
$(document).ready(function(){
function generation() {
this.var1 = '';
.... // some variables
this.genFactory = function(agents) { // some function that creates even more
objects and other functions
};
};
});
Timeline.JS:
这是我想创建生成对象实例的地方
$(document).ready(function(){
$('#start').click(function(){
console.log('ASD'); //just to check if the file works
gen1 = new generation(); //the error message points here
gen1.genFactory(3);
gen1.shuffle(individuals); //this is just an other method of the
generation object
});
});
只是为了确保 Timeline.js 正常工作:控制台记录“ASD”。
期待任何建议!
最佳答案
您应该将您的generation
函数分配给窗口,从而向公众公开它。在这种情况下,一种通用的方法是使用一个包含所有此类对象构造函数和变量的 app
变量。在您的 Generation.js 文件中,您应该使用以下代码:
$(document).ready(function(){
window.app = window.app || {};
app.generation = function () {
this.var1 = '';
.... // some variables
this.genFactory = function(agents) { // some function that creates even more
objects and other functions
};
};
});
在您的 Timeline.js 文件中,您将按如下方式调用您的构造函数:
$(document).ready(function(){
window.app = window.app || {};
$('#start').click(function(){
console.log('ASD'); //just to check if the file works
gen1 = new app.generation(); //the error message points here
gen1.genFactory(3);
gen1.shuffle(individuals); //this is just an other method of the
generation object
});
})
关于javascript - 通过位于单独的 js 文件中的 JS 中的对象构造函数创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24245238/