What Object.defineProperty and Proxy Have in Common

While reading the Vue documentation, I noticed something interesting.

The use of Object.defineProperty and the new Proxy feature have some similarities. Quite interesting.

The docs say:

When a plain JavaScript object is passed to the Vue instance’s data option, Vue iterates over all of its properties and converts them to getter/setters using Object.defineProperty.

Object.defineProperty

Syntax:

Object.defineProperty(obj, prop, descriptor)
  • obj: Required. The target object.
  • prop: Required. The name of the property to define or modify.
  • descriptor: Required. The descriptor for the target property.

Return value:

The object passed to the function, i.e., the first parameter obj.

getter/setter Accessor Descriptor

When using an accessor descriptor to define a property, you can set the following attributes:

var obj = {};
Object.defineProperty(obj,"newKey",{
    get:function (){} | undefined,
    set:function (value){} | undefined
});

You can provide getter/setter methods when getting or setting an object’s property value.

var obj = {};
var initValue = 'hello';
Object.defineProperty(obj,"newKey",{
    get:function (){
        // Triggered when getting the value
        return initValue;    
    },
    set:function (value){
        // Triggered when setting the value, the new value is available through the value parameter
        initValue = value;
    }
});
// Get value
console.log( obj.newKey );  //hello

// Set value
obj.newKey = 'change value';

console.log( obj.newKey ); //change value

Isn’t that amazing?

But seeing this, I suddenly remembered Proxy from ES6 that I mentioned in a previous article.

Here’s an example:

var obj={
  a:1
}
var proxyObj =  new Proxy(obj,{ //proxyObj will inherit obj
    set:function(){
      alert("I've been modified")
    },
    get:function(){
        alert("I've been accessed")
    }
  });

  // Modify property
  proxyObj.a=2; // After the property is modified, the previously set handler is triggered
  console.log(obj.a) // 2

That’s it for today. Happy Children’s Day!

Article Link:

/en/archive/defineproperty-vs-proxy/

# Related Articles