为什么我不能通过 Javascript 中的函数构造函数创建纯对象?
Why I cannot create a pure object via a function-constructor in Javascript?
我有一个关于 Javascript 继承的问题。我想创建一个纯对象。我可以使用 Object.create(null)
来完成。但是我决定通过构造函数来创建它。
let User = function () {};
User.prototype = null;
所以现在我可以预料,每个使用 new User()
语法创建的对象都没有任何原型。
但是
let user = new User();
console.log(user.__proto__ == Object.prototype); //true
这里为什么不为空?为什么这里不纯?我想我遗漏了一些重要的东西。
proto getter 函数公开对象内部 [[Prototype]] 的值。对于使用对象文字创建的对象,此值为 Object.prototype。比较对象“user”的内部 [[Prototype]] 的值:
console.log(user.__proto__ == Object.prototype.__proto__); //false
enter image description here
Now I can expect, that every object created with new User()
syntax, will have no prototype whatsoever.
是的,这是一个合理的期望,但 JS 并不是那样工作的。如果构造函数的 .prototype
不是对象,则 new
运算符回退到从 Object.prototype
创建对象。只有 ES5 引入了一种方法来创建继承自 null
和 Object.create
.
的纯对象
我有一个关于 Javascript 继承的问题。我想创建一个纯对象。我可以使用 Object.create(null)
来完成。但是我决定通过构造函数来创建它。
let User = function () {};
User.prototype = null;
所以现在我可以预料,每个使用 new User()
语法创建的对象都没有任何原型。
但是
let user = new User();
console.log(user.__proto__ == Object.prototype); //true
这里为什么不为空?为什么这里不纯?我想我遗漏了一些重要的东西。
proto getter 函数公开对象内部 [[Prototype]] 的值。对于使用对象文字创建的对象,此值为 Object.prototype。比较对象“user”的内部 [[Prototype]] 的值:
console.log(user.__proto__ == Object.prototype.__proto__); //false
enter image description here
Now I can expect, that every object created with
new User()
syntax, will have no prototype whatsoever.
是的,这是一个合理的期望,但 JS 并不是那样工作的。如果构造函数的 .prototype
不是对象,则 new
运算符回退到从 Object.prototype
创建对象。只有 ES5 引入了一种方法来创建继承自 null
和 Object.create
.