我不明白对象的可写和可配置属性。例如,在 MDN 中 Object.prototype ,有一张表,我可以清楚地看到 Object.prototype 的 Configurable、Writable 和 Enumerable Property Attributes 被锁定。
但是,我可以编写和扩展 Object.prototype,例如使用以下代码:
// Example 1
Object.prototype.testing=999;
console.log(Object.testing); // 999
// Example 2
var o = {};
console.log(o.testing); // 999
最佳答案
MDN指的是Object
本身的属性prototype
。您不能覆盖 Object.prototype
本身。如果您尝试使 Object.prototype
未定义,那将失败:
Object.prototype = 1;
console.log(Object.prototype); // [object Object]
如果您在严格模式下尝试此操作,您将在尝试分配给不可写属性时收到 TypeError
:
'use strict';
Object.prototype = 1; // TypeError: Cannot assign to read only property 'prototype' of function Object() { [native code] }
您可以在不更改对象引用的情况下写入对象自己的属性,并且这些属性具有单独的属性。例如,看这个:
var descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'toString');
console.log(descriptor.writable); // true
console.log(descriptor.enumerable); // false
console.log(descriptor.configurable); // true
有一个单独的 [[Extensible]]
内部属性可以防止在对象上创建新属性——如果您调用 ,它会被设置为
、false
>Object.preventExtensionsObject.seal
或 Object.freeze
。
请注意,在 Object.prototype
之类的对象上调用 Object.freeze
并不是一个好主意,因为可能会发生非常奇怪的事情:
Object.freeze(Object.prototype);
var building = {};
building.name = 'Alcove Apartments';
building.constructor = 'Meriton Apartments Pty Ltd';
console.log(building.constructor); // function Object() { [native code] }
就像前面的例子一样,它也会在严格模式下抛出一个TypeError
。
基本上,即使它是对象本身的属性,它也会使用原型(prototype)链中的属性来检查它是否可以分配该属性。这一直是considered as a mistake某些人使用该语言,但其他人认为此行为是设计使然。
关于javascript - 我不明白对象的可写和可配置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960493/