使JavaScript变量只对同一个.js文件中的函数有效 [英] Make A javascript variable only avaliable to functions on the same .js file

查看:111
本文介绍了使JavaScript变量只对同一个.js文件中的函数有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript有点新,而且我被困在这个项目上。有人可以告诉我如何制作一个JavaScript变量,它只能在.js文件中使用。



示例:



假设我有两个.js文件,PG1& PG2。
PG1包含var channel = Channel01;

PG2包含一个名称相同但变量不同的变量
(等于sign)(var channel = Channel02)

我不希望PG1上的function1使用PG2上的变量或PG2上的function2来使用PG1上的变量。 / p>

我也从一个单独的HTML页面调用这些函数。



问题:我所有的函数最终都会使用无论他们在哪个页面上,只有一个变量。
(例如,函数1和函数2都使用var channel = channel01)

问题:如何限制页面1上的函数仅使用那些变量。 js page



谢谢!

解决方案

模式模式:

  var myModule =(function(exports){

var x =foo;

exports.myFunction = function(){
alert(x);
};

})(typeof exports!=undefined&& exports instanceof Object?exports:window);

myFunction 将会在 window 在浏览器中的作用域。

编辑

我引用作者的话:我也从一个单独的HTML页面调用这些函数。



所以作者需要全局访问函数he定义。



var myModule虽然不需要,但也不需要导出,它仅用于AMD兼容性:

 (function(exports){

var x =foo;

exports.myFunction = function(){
alert (x);
};

})(窗口);

现在x for myFunction只存在于闭包中,但myFunction仍然可以访问全局范围中的x。全球范围内的任何x定义或任何范围都不会影响 x =foo


I somewhat new to Javascript and I'm stuck on this one item. Can someone please show me how to make a javascript variable only usable on the .js file that it is on.

EXAMPLE:

Say I have two .js files, PG1 & PG2. PG1 contains var channel = Channel01;

PG2 contains a variable with the same name, but a different entered Variable (the part after the equals sign) (var channel = Channel02)

I don't want function1 on PG1 to use the variable on PG2 or for function2 on PG2 to use the variable on PG1.

I am also calling these functions from a seperate HTML page.

Problem: All of my functions end up using only one variable no matter what page they are on. (ex. function1 & function2 both use var channel = channel01)

Question: How can I limit functions on page1 to use only the variables on that .js page

Thanks!

解决方案

module pattern :

var myModule = (function(exports){

    var x = "foo";

    exports.myFunction = function(){
        alert(x);
    };

})(typeof exports!="undefined" && exports instanceof Object ? exports : window );

myFunction will be available in the window scope in the browser.

EDIT

i quote the author : "I am also calling these functions from a seperate HTML page."

so the author needs a global access to the functions he defines.

var myModule is not needed though , nor export , it is just for AMD compatibility :

(function(exports){

    var x = "foo";

    exports.myFunction = function(){
        alert(x);
    };

})(window);

now x for myFunction only exists in the closure , but myFunction can still access x in the global scope. any x definition in the global scope or whatever scope will not affect x = "foo"

这篇关于使JavaScript变量只对同一个.js文件中的函数有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆