Object.defineProperty 接口浏览器实现的bug.和疑惑
Adds a property to an object, or modifies attributes of an existing property.
Object.defineProperty(object, propertyname, descriptor)
- object
-
Required. The object on which to add or modify the property. This can be a native JavaScript object or a DOM object.
(can be 不等于 must be啊. IE8到底搞什么?另外Safari并不允许DOM object.)
- propertyname
-
Required. A string that contains the property name.
- descriptor
-
Required. A JavaScript object that is a descriptor that describes the property. The definition can be for a data property or an accessor property.
You can use the
Object.defineProperty function to do the following:
-
Add a new property to an object. This occurs when the object does not have the specified property name.
-
Modify attributes of an existing property. This occurs when the object already has the specified property name.(参考后面的注释1)
The property definition is provided in a descriptor object, which describes the attributes of a data property or an accessor property. The descriptor object is a parameter of theObject.defineProperty function.
descriptor 参数: (参考 ECMA262 Edition5 8.12.9章节)
Data descriptor attribute |
Description |
Default if not specified when you add a property |
---|---|---|
value |
The current value of the property. |
undefined |
writable |
true or false. If writable is set to true, the property value can be changed. |
false |
enumerable |
true or false. If enumerable is set to true, the property can be enumerated by a for…in statement. |
false |
configurable |
true or false. If configurable is set to true, property attributes can be changed, and the property can be deleted. |
false |
1. IE8,普通的 new Object 无法使用此接口.
Object.defineProperty(o,'abc',{value:123}); //抛出异常,不是因为别的.仅仅因为 o是一个普通的js object.
o.abc = 300
alert(o.abc);
2.IE8 Configurable:false
Object.defineProperty(o,'abc',{value:123,Configurable:false});
delete o.a //IE8此处抛出异常.
alert(o.abc);
abc = 200;
window.abc = 300;
alert([abc,window.abc]) // ie8,Safari5 300,300 | Chrome,Ie9 123,123
var o = {abc:123};Object.defineProperty(o,'abc',{value:200,Writable:false});
o.abc = 300;
alert(o.abc)//支持defineProperty的浏览器都打印300. 即Writable:false,失效了