簡體   English   中英

我不明白對象的可寫和可配置屬性

[英]I don't understand writable and configurable property attributes of Objects

我不明白對象的 Writable 和 Configurable 屬性。 比如在 MDN for Object.prototype 中,有一張表,可以清楚地看到Object.prototype 的Configurable、Writable 和 Enumerable 屬性被鎖定。

但是,我可以編寫和擴展 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]]內部屬性可以防止在對象上創建新屬性——如果您調用Object.preventExtensionsObject.sealObject.freeze ,則該屬性設置為false

請注意,在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

基本上,即使它是對象本身的屬性,它也會使用原型鏈中的屬性來檢查它是否可以分配該屬性。 有些人認為這是語言中的錯誤,但其他人認為這種行為是設計使然。

來自: http : //ejohn.org/blog/ecmascript-5-objects-and-properties/

Writable:如果為false,則無法更改該屬性的值。

Configurable:如果為 false,則任何刪除屬性或更改其屬性(Writable、Configurable 或 Enumerable)的嘗試都將失敗。

可枚舉:如果為 true,則當用戶執行 for (var prop in obj){}(或類似操作)時,將迭代該屬性。

MDN 中的 Writable、Enumerable 和 Configurable 屬性似乎與Object.prototype對象本身有關,而不是它的屬性。

所以,這意味着你不能用不同的對象替換Object.prototype ,但你可以向它添加屬性。

所以,這意味着如果你這樣做:

Object.prototype = {foo: "whatever"};   // doesn't work - is just ignored
var j = {};
console.log(j.foo);   // undefined

然后,第一行代碼不會做任何事情。

我可以清楚地看到 Object.prototype 的 Configurable、Writable 和 Enumerable 屬性被鎖定。 但是,我可以編寫Object.prototype

不,可寫性只涉及Object對象的prototype屬性:

Object.prototype = {}; // Error: Invalid assignment (in strict mode)
                       // simply fails in lax mode

我可以擴展Object.prototype

是的。 您可以擴展Object.prototype對象(無論您如何引用它); 這是一個不同的屬性(對象的,而不是單個屬性的):

var proto = Object.getPrototypeOf({});
proto.testing1 = 9999; // works
Object.preventExtensions(proto);
proto.testing2 = 9999; // Error: Invalid assignment (in strict mode)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM