var _global = typeof window === 'undefined' ? global : window;
关于global 全局变量的使用。
使用node换进和web开发的前端同学应该都大概了解。
global 是nodejs环境
window是web换进。以下做两个具体例子进行分析说明:
对于 null 和undefined 需要进行注意:
【在开发中我们常常要进行非空判断,而 JavaScript 中有两种特殊数据类型:undefined 和 null:
-
null: Null 类型,表示“空值”,代表一个空对象指针,使用 typeof 运算得到 “object”,所以我们可以认为它是一个特殊的对象值。
-
undefined: Undefined 类型,当声明了一个变量未初始化时,得到的就是 undefined。
】
nodejs环境:
web环境
具体代码如下:
//nodejs 环境
function testF(testParam) {
console.log('testParam: ', testParam);//undefined
/* 下面的写法会报错
//假如一个变量连声明都没有声明,这么写会报错,需要写成typeof【because window is not defined】
// if (window) {
// console.log('window 存在', window);
// }
*/
console.log('global: ', global);
console.log('typeof window: ', typeof window);//undefined
var _global = typeof window === 'undefined' ? global : window;
_global.cc = _global.cc || {};
console.log(cc);//{}
console.log(_global === global)//true
}
testF();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
function testF(testParam) {
console.log("testParam: ", testParam); //undefined
/* 浏览器环境 下面的写法会报错
//假如一个变量连声明都没有声明,这么写会报错,需要写成typeof【because global is not defined】
if (global) {
console.log("global: ", global);
}
*/
console.log("window 存在", window);
console.log("typeof window: ", typeof window); //undefined
var _global = typeof window === "undefined" ? global : window;
}
testF();
</script>
</body>
</html>