为什么不能将属性添加到空值? [英] Why can't a property be added to a null value?

查看:126
本文介绍了为什么不能将属性添加到空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 null javascript的值是一个空对象,为什么不能为它添加属性?
以下代码清除了我的问题:

If null value of javascript is an empty object so why can't add a property to it? the below code clears my question:

var a = null;

typeof a;
>>> "object"

a.name = 'name';
>>> TypeError: Cannot set property 'name' of null

var a = new Object();

typeof a;
>>> "object"

a.name = 'name';
>>> "name"


推荐答案

根据定义, null value, undefined 值具有任何属性,也不能添加任何属性。

By definition neither the null value nor the undefined value have any properties, nor can any properties be added to them.

null 很好地总结了这一点:

This is summarized nicely for null:


原始表示故意缺少任何对象值。

primitive value that represents the intentional absence of any object value.

同样,对于 undefined


原始表示故意缺少任何对象值。

primitive value that represents the intentional absence of any object value.

null 是Null类型的唯一值, undefined 是唯一的值未定义类型。)

(null is the only value of the Null-type and undefined is the only value of the Undefined-type.)

这两种类型都代表原语和内部ToObject方法涵盖primitiveValue.Property的行为。 (有关兔子洞的开始,请参见 GetValue / PutValue 。)

Both of these types represent primitives and the behavior of "primitiveValue.Property" is covered by the internal ToObject method. (See GetValue/PutValue for the start of the rabbit hole.)

来自 9.9:ToObject


抽象操作ToObject根据..将其参数转换为Object类型的值。

The abstract operation ToObject converts its argument to a value of type Object according to ..


  • Undefined =>抛出TypeError异常。

  • Null => 抛出TypeError异常。

  • (依此类推)

至于评论,请参阅 11.4.3:typeOf运算符


根据..返回由Type(val)确定的字符串。

Return a String determined by Type(val) according to ..


  • Undefined =>undefined

  • Null => object

  • (依此类推)

这篇关于为什么不能将属性添加到空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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