我目前正在尝试了解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
。
答案 0 :(得分:5)
这是由于原型链上的属性阴影所致。执行时
[].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);
答案 1 :(得分:1)
.__proto__
是单个变量。当您在所有实例上对其进行修改时,将对其进行修改。两个不同数组中的__proto__
是相同的。
console.log([].__proto__ === [1,23,3123].__proto__) //true
但是当您更改数组constructor
的实例的[]
属性时。它不会更改所有实例中的所有__proto__
。
console.log([] === []) //false
但是,如果将数组存储在变量中,然后更改其属性,它将起作用。
let arr = [];
arr.constructor = function A(){}
console.log(arr.constructor)