gpt4 book ai didi

javascript - 为什么 null 没有 __proto__?

转载 作者:行者123 更新时间:2023-12-03 10:05:32 26 4
gpt4 key购买 nike

null 在 JS 中被认为是一个对象。 typeof null == "object"//真

那为什么 null 没有 __proto__。所有对象都应该在 JS 中有一个 __proto__

var n = null;
console.log(n.__proto__); //Cannot read property '__proto__' of null`

有人可以提供详细的答案吗?

最佳答案

null in JS is considered as an object. typeof null == "object" //true

前面已经提到,null实际上是一个原始值(如undefined,一个 bool 值,一个String值,一个Number值,或一个符号)。但是语言规范规定 typeof null 返回字符串 "object"。 (类似地,规范规定为 函数对象 返回 "function" 而不是 "object",就像它为 array objects)

但这只是故事的一半。

Then why does null not have a __proto__

你可能想知道:

Why can I access the protoype of a string value ("foo".__proto__) but not null if both are primitive values ?

那是因为 bool 值、字符串和数字具有对象等价物(例如 new String("foo")),当您尝试访问 bool 值/数字/字符串基元上的属性时,它们在内部是转换为对象值

console.log("foo".slice)
// does `new String("foo").slice` internally

但是对于 undefinednull,不存在这样的对象等价物,因此会出现错误。

try {
console.log(null.foo);
} catch(e) {
console.log(e.message);
}

try {
console.log(undefined.foo);
} catch(e) {
console.log(e.message);
}

All objects should have a __proto__ in JS

不一定。可以通过 Object.create 创建没有原型(prototype)的对象:

const obj = Object.create(null);
console.log(obj.__proto__);

关于javascript - 为什么 null 没有 __proto__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com