Search code examples
javascriptobjectconstructores6-proxy

How to set proxy on constructor function


I have a constructor function like this:

function a(p){
this.k=12;
this.f = p;
this.t = function(){};
}

Now let say i create a object with this function:

let obj = new a("tf");

I can always do this to check if a new property assigned to object:

obj = new Proxy(obj,{set:()=>{console.log("new property assigned!");return true;}})
//Now if i were to say
obj.property1 = 12
//It will log out "new property assigned!"

But the problem is, that i have to do this for every new object i create with this constructor function. So what i want to do is whenever i create a new object like this:

let newObj = new a();

I want to set my proxy automatically.

How can i achieve this?


Solution

  • Write a factory function in which you create a new instance of your object while also adds a Proxy to the newly created instance.

    function proxyFactory(Class, ...args) {
      const instance = new Class(...args);
      return new Proxy(instance, {
        set: () => {
          console.log("new property assigned!");
          return true;
        }
      });
    }
    

    And then call the factory function with the class and the arguments you want to apply.

    let newObj = proxyFactory(a, "tf");