我在short中的问题是:我已经在js文件中创建了一个对象构造函数(文件名: generation.js),并且我希望在另一个js文件(文件名: timeline.js)中使用该构造函数创建一个对象。当我尝试这样做时,我会得到错误消息: Uncaught : generation (我想要创建的对象)没有定义。
在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‘。
期待任何建议!
发布于 2014-06-16 13:53:06
您应该通过将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
});
})https://stackoverflow.com/questions/24245238
复制相似问题