我目前正在尝试理解javascript中的constructor属性。
只是提醒一下,我知道应该避免改变内置的属性,我只是在玩弄它,因为我想更好地理解基本的原则。
我试图更改默认的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
所以我尝试通过constructor设置[].__proto__属性,它成功了。
[].__proto__.constructor = function B(){};
[].__proto__.constructor; // prints: ƒ B(){}, which indicate the attempt succeded为什么通过constructor更改[]失败,但通过[].__proto__更改成功?尽管[].constructor === [].__proto__.constructor返回了true。
发布于 2019-03-29 05:15:17
这是由于在原型链上的属性阴影。当你执行
[].constructor = ...;这将在数组上创建一个实例属性,该属性隐藏类原型构造函数。但是,由于Array.prototype已经拥有自己的constructor属性,所以执行
[].__proto__.constructor = ...;覆盖Array.prototype上的构造函数。
您可以通过实际存储数组实例并仔细查看其原型链来确认此行为:

下面验证赋值是否在array1上实际创建了自己的属性,该属性隐藏了从Array.prototype继承的属性。
function A(){}
var array1 = [];
array1.constructor = A;
console.log(array1.constructor === A);
console.log(array1.__proto__.constructor === Array);
https://stackoverflow.com/questions/55410862
复制相似问题