【问题标题】:Creating an object through an object constructor in JS that is located in a separate js file通过位于单独 js 文件中的 JS 中的对象构造函数创建对象
【发布时间】:2014-06-16 13:45:02
【问题描述】:

short 中的问题:我在 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”。

期待任何建议!

【问题讨论】:

    标签: javascript file object constructor external


    【解决方案1】:

    您应该通过将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
    
       });
    })
    

    【讨论】:

    • 除非你在某处明确分配window.app,否则两个闭包最终都会分配给它们自己的本地vars。
    • 是的,很抱歉,已修复:)
    • 谢谢!有效!你能解释一下这段代码到底是做什么的吗?我猜它创建了一个继承自 window 的 app 对象。为什么我必须在两个文件中都包含该行?
    • 它将一个对象附加到窗口,不会创建一个继承自它的对象。您必须在两个文件中都包含该行,以防一个在另一个之前加载。这样,您将在两个文件中使用相同的对象实例。
    猜你喜欢
    • 2016-07-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多