如何为单个类设置原型对象的属性

时间:2018-12-03 20:15:23

标签: javascript prototype

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

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

然后,我将test的属性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的原型

1 个答案:

答案 0 :(得分:1)

在您的示例中,// If this condition is met, the first argument is chosen, if not, the second one // is chosen, this condition checks if the input is ColMajor or RowMajor, all of // the tests I've done result in a RowMajor but I don't know what determines this // exactly return choose( Cond(), // ColMajor kernel.reshape(kernel_dims) .contract(input .extract_image_patches( kernelRows, kernelCols, row_stride, col_stride, row_in_stride, col_in_stride, padding_type) .reshape(pre_contract_dims), contract_dims) .reshape(post_contract_dims), // RowMajor input.extract_image_patches(kernelRows, kernelCols, row_stride, col_stride, row_in_stride, col_in_stride, padding_type) .reshape(pre_contract_dims) .contract(kernel.reshape(kernel_dims),contract_dims).reshape(post_contract_dims)); 没有自己的Array.protoype属性。因此,当您尝试使用test访问它时,它将查找原型链并在Array.prototype.test.abc = 20;上找到.test对象,并设置 its Object.prototype的值到20。

您可以为.abc拥有自己的财产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对象从Array链接到Object,因此在test上找不到的属性将把该链延迟到Array.prototype.test,尽管这开始变得令人困惑:

Object.prototype.test

...不是我真的建议您在测试和探索生态系统之外的任何方式。