Skip to content Skip to sidebar Skip to footer

How To Intercept A Known Property Value Assignment Of An Unknwon Object Created Using Literal Notation

This question is a continuation of another I asked here: How to intercept and modify a specific property for any Object This is a method used to intercept any object's property of

Solution 1:

There's no way I know of to achieve the effect you're looking for. An assignment with = will cause your object to go through the Prototype chain and use the get method on the Object prototype. However, a literal assignment will place it directly on your new object. It's the rules of Javascript. For more information I'd suggest reading You Don't Know JS, This & Object Prototypes, Chapter 5, specifically the Setting & Shadowing Properties section.

Relevant part:

We will now examine three scenarios for the myObject.foo = "bar" assignment when foo is not already on myObject directly, but is at a higher level of myObject's [[Prototype]] chain:

  1. If a normal data accessor (see Chapter 3) property named foo is found anywhere higher on the [[Prototype]] chain, and it's not marked as read-only (writable:false) then a new property called foo is added directly to myObject, resulting in a shadowed property.
  2. If a foo is found higher on the [[Prototype]] chain, but it's marked as read-only (writable:false), then both the setting of that existing property as well as the creation of the shadowed property on myObject are disallowed. If the code is running in strict mode, an error will be thrown. Otherwise, the setting of the property value will silently be ignored. Either way, no shadowing occurs.
  3. If a foo is found higher on the [[Prototype]] chain and it's a setter (see Chapter 3), then the setter will always be called. No foo will be added to (aka, shadowed on) myObject, nor will the foo setter be redefined. Most developers assume that assignment of a property ([[Put]]) will always result in shadowing if the property already exists higher on the [[Prototype]] chain, but as you can see, that's only true in one (#1) of the three situations just described.

If you want to shadow foo in cases #2 and #3, you cannot use = assignment, but must instead use Object.defineProperty(..) (see Chapter 3) to add foo to myObject.

Post a Comment for "How To Intercept A Known Property Value Assignment Of An Unknwon Object Created Using Literal Notation"