【发布时间】:2019-08-20 00:10:04
【问题描述】:
我目前正在尝试了解 javascript 中的 constructor 属性。
提醒一下,我知道应该避免更改 builtin 的属性,我正在玩弄它,因为我想更好地理解基本原理。
我尝试更改[] 的默认constructor 属性(即数组对象的默认构造函数)
[].__proto__.constructor === [].constructor; // true
[].constructor = function A(){}; // attempts to reset the constructor property to a new function
[].constructor; // prints ƒ Array() { [native code] }, which indicate the attempt failed
但是当我检查[].constructor的属性描述符时
Object.getOwnPropertyDescriptor([].__proto__, 'constructor');
打印出来的
{value: ƒ, writable: true, enumerable: false, configurable: true}
所以[].__proto__.constructor 属性是writable?
于是我尝试通过[].__proto__设置constructor属性,成功了
[].__proto__.constructor = function B(){};
[].__proto__.constructor; // prints: ƒ B(){}, which indicate the attempt succeded
为什么通过[] 更改constructor 属性失败但通过[].__proto__ 成功?尽管[].constructor === [].__proto__.constructor 返回了true。
【问题讨论】:
标签: javascript arrays constructor prototype