I try to understand why the variable 'Permissions' will be typeof 'function' when Permissions declared with var but typeof 'object' when declared with let (which is the excepted behavior)
我试图理解为什么当用var声明权限时,变量‘Permises’的类型是‘Function’,而当用let声明时,变量的类型是‘Object’(这是例外行为)
With 'var' - Permissions is typeof 'function'
With‘var’-权限类型为‘Function’
var Permissions;
(function (Permissions) {
Permissions[Permissions["ADMIN"] = 0] = "ADMIN";
Permissions[Permissions["READ_ONLY"] = 1] = "READ_ONLY";
})(Permissions || (Permissions = {}));
console.log(typeof Permissions);
With 'let' - Permissions is typeof 'object'
WITH‘let’-权限类型为‘Object’
let Permissions;
(function (Permissions) {
Permissions[Permissions["ADMIN"] = 0] = "ADMIN";
Permissions[Permissions["READ_ONLY"] = 1] = "READ_ONLY";
})(Permissions || (Permissions = {}));
console.log(typeof Permissions);
I excepted both scenario to be 'object'. why using 'var' Permissions is typeof 'function'?
我认为这两种情况都是“对象”。为什么使用‘var’权限是‘Function’类型?
更多回答
try just var Permissions; console.log(typeof Permissions)
it has nothing to do with IIFE - all to do with Permissions API and the subtle difference between var and let
尝试只使用var权限;console.log(类型的权限)它与生活无关-所有这些都与权限API以及var和let之间的细微差别有关
优秀答案推荐
Declaring a variable with var
in a global scope makes it a property of window
.
Since you haven't initialized it, it's actually pointing to the existing window.Permissions
property, which is a constructor of navigator.permissions
.
在全局范围内使用var声明变量使其成为Window的属性。由于您尚未对其进行初始化,因此它实际上指向现有的window.Permission属性,该属性是Navigator.Permises的构造函数。
let
works differently and declares a separate variable in the current scope:
Let的工作方式不同,它在当前作用域中声明了一个单独的变量:
console.log(Permissions);
console.log(navigator.permissions.__proto__ === Permissions.prototype);
var test = 'test';
console.log(window.test);
If you put your var
into a function scope, it would work like let
:
如果您将var放入一个函数作用域,它的工作方式类似于let:
(function(){
var Permissions;
(function (Permissions) {
Permissions[Permissions["ADMIN"] = 0] = "ADMIN";
Permissions[Permissions["READ_ONLY"] = 1] = "READ_ONLY";
})(Permissions || (Permissions = {}));
console.log(typeof Permissions);
})();
Also works as let
in a module scope:
也可以作为模块作用域中的let使用:
<script type="module">
var Permissions;
(function (Permissions) {
Permissions[Permissions["ADMIN"] = 0] = "ADMIN";
Permissions[Permissions["READ_ONLY"] = 1] = "READ_ONLY";
})(Permissions || (Permissions = {}));
console.log(typeof Permissions);
</script>
With this and other many problems inherited to var
I treat var
as legacy and dangerous and prohibit it with ESLint.
由于var继承了这个和其他许多问题,我将var视为遗留的和危险的,并使用ESLint禁止它。
更多回答
我是一名优秀的程序员,十分优秀!