无法理解在JavaScript中删除var的行为 [英] Can't understand the behavior of deleting vars in JavaScript

查看:41
本文介绍了无法理解在JavaScript中删除var的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题出在这里:

var x = 5;
window.x === x // true. x, as it seems, is a property of window
delete x; // false
delete window.x; // false;

但是

window.x = 5;
delete window.x; // true

AND

window.x = 5;
delete x; // true

这种行为的解释是什么?

What is the explanation for such behavior?

推荐答案

基本上,原因是声明的变量是使用内部 DontDelete 属性创建的,而通过赋值创建的属性不是.

Essentially the reason is that declared variables are created with an internal DontDelete attribute, while properties created via assignment are not.

这是一篇很棒的文章,解释了 delete 的内部细节:了解删除

Here is great article explaining the inner details of delete: Understanding delete

当声明的变量和函数成为变量的属性时对象-激活对象(用于功能代码)或全局对象(对于全局代码),这些属性是使用DontDelete创建的属性.但是,任何显式(或隐式)属性分配创建没有DontDelete属性的属性.这是必不可少的为什么我们可以删除某些属性,但不能删除其他属性:

When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute. However, any explicit (or implicit) property assignment creates property without DontDelete attribute. And this is essentialy why we can delete some properties, but not others:

这篇关于无法理解在JavaScript中删除var的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆