1

假设我像这样更改对象原型:

Object.prototype.test = {val: 5, abc: 8};

然后我更改testfor的属性Array

Array.prototype.test.abc = 20;

然后,如果我打印基本test变量:

console.log(Object.prototype.test); // {val: 5, abc: 20}
console.log(({}).test);        // {val: 5, abc: 20}
console.log(([]).test);       // {val: 5, abc: 20}

我如何仍然让数组继承val为 5,但abc值为 20 而不会影响Object原型

4

1 回答 1

1

在您的示例Array.protoype中没有自己的test属性。因此,当您尝试使用它访问它时,Array.prototype.test.abc = 20;它会查找原型链并找到.test对象Object.prototype并将 .abc值设置为 20。

你可以给Array.prototype它自己的财产test,比如:

Object.prototype.test = {val: 5, abc: 8};

Array.prototype.test = Object.assign({}, Object.prototype.test)
Array.prototype.test.abc = 20;

console.log(({}).test.abc);       // 8
console.log(([]).test.abc);       // 20

您还可以将test对象从 Array 链接到 Object ,以便在未找到的属性Array.prototype.test将链推迟到Object.prototype.test,尽管这开始变得令人困惑:

Object.prototype.test = {val: 5, abc: 8};

Array.prototype.test = Object.create(Object.prototype.test)
Array.prototype.test.abc = 20;

console.log(([]).test.abc);      // shadows with it's own abc
Object.prototype.test.abc = 500  // changes in object have no effect
console.log(([]).test.abc);      // still 20

console.log(([]).test.val);      // no val on Array's test so it defers to object prototype
Object.prototype.test.val = 100  // changing object changes array
console.log(([]).test.val); 

…并不是说我真的推荐任何超越测试和探索生态系统的东西。

于 2018-12-03T20:29:59.007 回答