简体   繁体   English

了解JavaScript中的变量阴影?

[英]understanding variable shadowing in javascript?

i created a crypto object as follows: 我创建了一个加密对象,如下所示:

 var crypto = { encrypt: function(s) { } }; crypto.encrypt("cat"); 

I would get the following error 我会收到以下错误

Uncaught TypeError: crypto.encrypt is not a function 未捕获的TypeError: crypto.encrypt不是函数

 var crypt = { encrypt: function(s) { } }; crypt.encrypt("cat"); 

this would work. 这会工作。 I realized that there is already an inbuilt crypto object so the crypto object i defined was not being recognized. 我意识到已经有一个内置的crypto对象,因此无法识别我定义的加密对象。

My understanding is that the variables declared later will shadow variable declared previously. 我的理解是,稍后声明的变量将覆盖之前声明的变量。

For example when i create two objects like follows: 例如,当我创建两个对象时,如下所示:

 var test = { testing2: function() { return "there"; } } var test = { testing: function() { return "hey"; } } test.testing2() 

and i call test.testing2() then the similar error is thrown because the second test variable has shadowed the first. 我打电话给test.testing2()然后抛出类似的错误,因为第二个测试变量test.testing2()了第一个。 So if variable shadowing works with self created variables then why is crypto not being shadowed? 因此,如果变量影子可用于自创建变量,那么为什么不加密加密货币呢? Is it the case that the predefined objects are always higher in priority so any self created objects will not shadow the window objects. 是否存在这样的情况,即预定义对象的优先级始终较高,因此任何自行创建的对象都不会遮盖窗口对象。 I appreciate any insights into this. 我对此表示感谢。 Thanks! 谢谢!

Usually , yes, variables declared later (with var ) will simply overwrite var s declared earlier with the same name. 通常 ,是的,稍后声明的变量(使用var )将简单地覆盖之前声明的具有相同名称的var The difference is that variables declared with var on the top level assign to window properties, and window.crypto is a property with a getter, but no setter: 区别在于,在顶层使用var声明的变量分配给window属性,而window.crypto是具有getter但不包含setter的属性:

 console.log( Object.getOwnPropertyDescriptor(window, 'crypto') ); 

So when you assign to window.crypto with var crypto , there's no setter, so nothing happens. 因此,当您使用var crypto分配给window.crypto时,没有设置器,因此什么也没有发生。 Many other window properties behave the same way. 许多其他window属性的行为方式相同。

Consider using const or let instead: 考虑使用constlet代替:

 const crypto = { encrypt: function(s) { } }; crypto.encrypt("cat"); 

Or put it into an IIFE: 或将其放入IIFE:

 (() => { var crypto = { encrypt: function(s) { } }; crypto.encrypt("cat"); })(); 

Or use a linter 使用短绒

You can also use use strict to make the error explicit: 您也可以使用use strict使错误明确:

 'use strict'; var crypto = { encrypt: function(s) { } }; console.log('successfully defined crypto'); crypto.encrypt("cat"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM