[英]why inside function we can override “undefined” but can't in window object in JS…Example is given Below
I have given two different code. 我给了两个不同的代码。 One inside global
window
object and second inside foo
function 一个内部全局
window
对象,另一个内部foo
函数
Here my First code: 这是我的第一个代码:
var undefined = 2; // 2 console.log(undefined == 2); // it gives me FALSE var window = 5; // 5 console.log(window == 5); // it gives me FALSE var a; console.log(a); // it give me UNDEFINED
Here my second code: 这是我的第二个代码:
function foo() { var undefined = 2; // 2 console.log(undefined == 2); // true var window = 5; // 5 console.log(window == 5); // true var a; console.log(a); } foo();
window
and undefined
are predefined (by the JS engine / browser) variables. window
和undefined
是预定义的(通过JS引擎/浏览器)变量。
You can't overwrite a read only variable (if a variable already exists, then using var
in the scope it exists in does nothing). 您不能覆盖只读变量(如果变量已经存在,则在存在它的作用域中使用
var
不会执行任何操作)。
You can declare a new variable, in a narrower scope, that masks one with the same name in a wider scope. 您可以在较窄的范围内声明一个新变量,该变量将在较宽的范围内屏蔽具有相同名称的变量。
The global scope won't let you mess with just anything. 全局范围不会让您一团糟。 That would basically cause all sorts of bad things to happen.
从根本上讲,这将导致各种不良事件的发生。 That's why you can't change the things outside.
这就是为什么您无法更改外部内容的原因。
Inside the function, in an isolated scope, it'll let you declare variables with other names. 在函数内部,在隔离的范围内,它将允许您使用其他名称声明变量。 While this is an absolutely horrible practice and you should avoid it at all costs, it won't affect anything beyond the one function.
虽然这是绝对可怕的做法,但您应该不惜一切代价避免这样做,但它不会影响一个功能以外的任何功能。
function foo() {
var window = 5;
}
The window
in the function is not the same as the window
at the global level. 该
window
中的功能是不一样的window
在全球层面。 The window
in the function is simply masking the outer window, making it inaccessible from inside of foo
. 该函数中的
window
只是掩盖了外部窗口,使其无法从foo
内部访问。
In Your function foo() console.log(undefined == 2)
you mentioned //true is returning. 在函数
foo() console.log(undefined == 2)
您提到// true正在返回。 But actually it return "false". 但实际上它返回“ false”。 Because "undefined" is a reserved keyword.
因为“未定义”是保留关键字。 So you can't use this as a variable.
因此,您不能将其用作变量。 See images: When using undefined keyword it's not working
查看图片: 使用undefined关键字时,它不起作用
Better use some other variable name in your foo()
When using some other variable 在使用其他变量时,最好在
foo()
使用其他变量名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.