网站首页 » » 共享变量

共享变量

June 15, 2023
(function(global) {

var hello = 'abc';

global.hello = hello; // 将当前闭包内的某个变量绑定到全局环境

}) (this);

这里有一个知识点,就是:
传统浏览器中的javascript环境,全局对象的this默认绑定的是window实例,而全局环境的变量,默认会绑定到window对象上,也即成为window对象的属性。比如:

<head>
<script type="text/javascript">
var test = 'test';
</script>
</head>
<body>
<script type="text/javascript">
console.log(this.test); // test
console.log(window.test); // test
console.log(test); // test
</script>
</body>

所以综上所述:

// a.js
(function(global, config) {

 
console.log(config); // 输出全局环境定义的变量config

var hello = 'abc';

global.hello = hello; // 将当前闭包内的某个变量绑定到全局环境

}) (this, this.config || {});
在某个html页面中:

<head>
<script type="text/javascript">
var config = { a: 'a' };
</script>
<script type="text/javascript" src="a.js"></script>
</head>
<body>
<script type="text/javascript">
console.log(hello);
</script>
</body>