我不明白对象的可写和可配置属性

Mic*_*cip 5 javascript prototype object

我不明白对象的 Writable 和 Configurable 属性。比如在Object.prototype的MDN中,有一张表,可以清楚的看到Object.prototype的Configurable, Writable and 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
Run Code Online (Sandbox Code Playgroud)

Qan*_*avy 4

MDN 指的是其本身prototype的属性Object。您无法覆盖Object.prototype自身。如果你尝试将其设置Object.prototype为未定义,则会失败:

Object.prototype = 1;
console.log(Object.prototype); // [object Object]
Run Code Online (Sandbox Code Playgroud)

TypeError如果您在严格模式下尝试此操作,您将在尝试分配给不可写属性时得到:

'use strict';
Object.prototype = 1; // TypeError: Cannot assign to read only property 'prototype' of function Object() { [native code] }
Run Code Online (Sandbox Code Playgroud)

您可以写入对象自己的属性,而无需更改对象的引用,并且这些属性具有单独的属性。例如,看这个:

var descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'toString');

console.log(descriptor.writable); // true
console.log(descriptor.enumerable); // false
console.log(descriptor.configurable); // true
Run Code Online (Sandbox Code Playgroud)

有一个单独的[[Extensible]]内部属性可以防止在对象上创建新属性 -false如果您调用Object.preventExtensions, Object.sealor ,则将其设置为Object.freeze

Object.freeze请注意,调用诸如 之类的东西并不是一个好主意Object.prototype,因为可能会发生非常奇怪的事情:

Object.freeze(Object.prototype);
var building = {};
building.name = 'Alcove Apartments';
building.constructor = 'Meriton Apartments Pty Ltd';
console.log(building.constructor); // function Object() { [native code] } 
Run Code Online (Sandbox Code Playgroud)

就像前面的例子一样,它也会TypeError在严格模式下抛出 a 。

基本上,即使它是对象本身的属性,它也会使用原型链中的属性来检查是否可以分配该属性。一些人认为这是语言中的错误,但其他人则认为这种行为是设计使然。