我是JS模块的新手,并对以下内容感到困惑:
y
并将其返回将导出它:// Outputs "hello"
(function (x) {
var y = x;
return y;
}('hello'));
// Outputs "y is not defined"
console.log(y);
y
并不返回它不会导出它:// Outputs "undefined"
(function (x) {
var y = x;
}('hello'));
// Outputs "y is not defined"
console.log(y);
y
并不返回它会将其置于全局范围内吗?// Outputs "undefined"
(function (x) {
y = x;
}('hello'));
// Outputs "hello"
console.log(y);
我了解前两个示例中发生了什么,但是第三种情况在做什么,为什么?
答案 0 :(得分:1)
在这种情况下,由于hello
被声明为没有y
或var
,因此输出将为let
,因此y
将处于global(window)范围内
// Outputs "undefined"
(function(x) {
y = x;
}('hello'));
// Outputs "hello"
console.log(y);
在这种情况下,y
是用var
关键字声明的,因此变量y
的范围在函数内部,并且不能在函数外部访问。因此它将抛出ReferenceError: y is not defined
。请注意,当引用不存在的变量时将抛出术语ReferenceError。在以下情况下,您尝试引用变量范围之外的变量
// Outputs "hello"
(function(x) {
var y = x;
return y;
}('hello'));
// Outputs "y is not defined"
console.log(y);
但是,如果将iife分配给变量,则可以获得返回值
let k = (function(x) {
var y = x;
return y;
}('hello'));
// Outputs "y is not defined"
console.log(k);