简体   繁体   English

为什么这个数组原型不起作用?

[英]Why doesn't this array prototype work?

I don't understand why array b[1] does not use f as a getter and setter yet array a does. 我不明白为什么数组b [1]不使用f作为getter和setter而数组a却使用f。 yet both are arrays. 但这两个都是数组。 what am I missing here? 我在这里想念什么?

function f(){
    print("in f");
 }


Object.defineProperty(Array.prototype, "0",
    { get : f, set:f});

var a=[];
var b=[1];

a[0]; // prints f
a[0]=1; //prints f
b[0]; // no print
b[0]=1; // no print

console.log("a is an array " + Array.isArray(a)); //a is an array true
console.log("b is an array " + Array.isArray(b));//b is an array true

var a = [] does one thing: it sets a as an instance of a new Array but without any members, so the prototype[0] is inherited. var a = []做一件事:它将a设置为new Array的实例,但是没有任何成员,因此prototype[0]被继承。

var b = [1] does two things: it sets b as an instance of a new Array (as with a ), but then sets subscript [0] = 1 directly (bypassing JavaScript's prototype system), which means [0] = 1 overwrites the " 0 th" property, thus avoiding your defineProperty in prototype[0] entirely. var b = [1]做两件事:将b设置为new Array的实例(与a ),然后直接设置下标[0] = 1 (绕过JavaScript的原型系统),这意味着[0] = 1 覆盖 “第0个”属性,从而完全避免了prototype[0] defineProperty

This works the same way with objects: 这与对象的工作方式相同:

Object.defineProperty( Object.prototype, "foo", { get: f, set: f } );

var a = {};
a.foo = 1; // will print "in f"

var b = { foo: 'a' }
b.foo = 1; // will not print "in f"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM