关于js里undefined的重写问题

本文探讨了在不同JavaScript作用域中undefined是否可被重写的问题,并通过实例验证了在ECMAScript5标准下,undefined在全局作用域为只读,而在函数作用域内则可被重写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Javascript Garden里读到这样一句话

The language also defines a global variable that has the value of undefined;this variable is also called undefined. However, this variable is neither a constant nor a keyword of the language. This means that its value can be easily overwritten.

他老人家的意思是,undefined可以被重写。那么问题就来了。
那么在ECMAScript 5里,undefined究竟能不能被重写呢?

首先我们看一个例子

//在window域下
var undefined = "now it's defined";
console.log(undefined); //输出undefined

很奇怪的,undefined的值根本没有改变。那么Garden里的那句话岂不是出错了(后来证实那句话是在ECMAScript5之前写的)?

不过我们再来看一个例子。

(function(){
    var undefined = 123;
    console.log(undefined);//输出123
})()

诶,这里的值居然被重写了。所以我们可以得到一个结论,undefined在function作用域下是可以重写的,但是在window作用域(全局变量时)下,无法被重写

另外,NaN、Infinity等等是不是一样的结论呢?我们可以看下下面的这句话。

The value properties NaN, Infinity, and undefined of the Global Object have been changed to be read-only properties.

这句话是说,全局对象的属性Nan、Infinity、undefined都被变成了“只读属性”。
那我们怎样检验这些变量的属性呢?

Object.getOwnPropertyDescriptor(window, "undefined");

通过这样一个方法我们可以得到结果

Object {value: undefined, writable: false, enumerable: false, configurable: false}

所以在window作用域下是重写不了的。

http://www.whohelpme.com/t/detail/31704.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值