简体   繁体   English

需要使用2个.js文件的帮助

[英]Need help using 2 .js files

Both .js files work with my code separately, but when I try to access a constructor from one it does not work. 这两个.js文件分别与我的代码一起使用,但是当我尝试从其中一个访问构造函数时,它不起作用。

//.js file 1 Ex

(function(){


var Colors = function(color1,color2) {
this.color1 = color1;
this.color2 = color2;
};

})();

I need to use these in my second file as if they where in the first. 我需要在第二个文件中使用它们,就像它们在第一个文件中一样。

//.js file 2

var colors = [
    new Colors('green','blue'),
    new Colors('green','blue')];

    console.log(colors[1] + colors[2]);

Can someone please let me know what I am doing wrong?? 有人可以让我知道我做错了吗?

(function(){


var Colors = function(color1,color2) {
this.color1 = color1;
this.color2 = color2;
};

})();

The point of the IIFE function wrapper here is to hide variables declared inside it. 这里的IIFE函数包装器的重点是隐藏在其中声明的变量。 You can just take it off in this case. 在这种情况下,您可以将其取下。 If your situation does require “private” variables like this, export the important parts globally somehow, eg 如果您的情况确实需要像这样的“私有”变量,请以某种方式将重要部分导出到全球,例如

var Colors = (function() {
    function Colors(color1, color2) {
        this.color1 = color1;
        this.color2 = color2;
    }

    return Colors;
})();

Or 要么

(function(global) {
    function Colors(color1, color2) {
        this.color1 = color1;
        this.color2 = color2;
    }

    global.Colors = Colors;
})(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM