通过JS中的对象构造函数创建对象,该对象位于单独的js文件中

时间:2014-06-16 13:45:03

标签: javascript file object constructor external

我在简短中的问题:我在js文件中创建了一个对象构造函数(文件名:generation.js),我想在另一个文件中创建一个带有该构造函数的对象js文件(文件名:timeline.js)。当我尝试这样做时,我收到错误消息:未捕获的ReferenceError:生成(我想要创建的对象)未定义。

在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'。

期待任何建议!

1 个答案:

答案 0 :(得分:2)

您应该将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

   });
})