user961346
user961346

Reputation: 301

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. 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

Upvotes: 0

Views: 66

Answers (1)

Dai
Dai

Reputation: 155145

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 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 "0th" property, thus avoiding your defineProperty in prototype[0] entirely.

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"

Upvotes: 1

Related Questions