0

I'm just fiddling around trying to understand how his is supposed to work, but this scenario has me confused.

Object.defineProperty(Object.prototype, 'a', {set: function() {console.log("Set!");} });

With that method, I assume any time I create an object called a, that function should fire. It works here:

a = {};
Set!

But not when nested like this:

test = {a:{}};

Am I misunderstanding something?

user1131308
  • 309
  • 4
  • 12

1 Answers1

0

The object literal {a: …} is creating a new object with an own property. It does not call any inherited setters for the property creation, in part to prevent JSON hijacking.

However, the following code will have the desired behaviour:

test = {};
test.a = {};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375