Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Proxy set() local property on inherited objects

According to MDN, handler.set() can trap Inherited property assignment:

Object.create(proxy)[foo] = bar;

In which case, how does one both monitor and allow local assignments on inherited objects?

var base = {
	foo: function(){
		return "foo";
	}
}

var proxy = new Proxy(base, {
	set: function(target, property, value, receiver){
		console.log("called: " + property + " = " + value, "on", receiver);
		//receiver[property] = value; //Infinite loop!?!?!?!?!
		//target[property] = value // This is incorrect -> it will set the property on base.
		
		/*
			Fill in code here.
		*/
		return true;
	}
})

var inherited = {}
Object.setPrototypeOf(inherited, Object.create(proxy));

inherited.bar = function(){
	return "bar";
}

//Test cases
console.log(base.foo); //function foo
console.log(base.bar); //undefined
console.log(inherited.hasOwnProperty("bar")) //true
like image 377
blackening Avatar asked Oct 21 '25 12:10

blackening


1 Answers

After some additional thought, i noticed that it intercepts 3 ops:

Property assignment: proxy[foo] = bar and proxy.foo = bar Inherited property assignment: Object.create(proxy)[foo] = bar
Reflect.set()

but not Object.defineProperty() which appears to be even lower level than the = operator.

Thus the following works:

var base = {
    foo: function(){
        return "foo";
    }
};

var proxy = new Proxy(base, {
    set: function(target, property, value, receiver){
        var p = Object.getPrototypeOf(receiver);
      
        Object.defineProperty(receiver, property, { value: value });   // ***
        return true;
    }
});

var inherited = {};
Object.setPrototypeOf(inherited, Object.create(proxy));

inherited.bar = function(){
    return "bar";
};

// Test cases
console.log(base.foo);                       // function foo
console.log(base.bar);                       // undefined
console.log(inherited.bar);                  // function bar
console.log(inherited.hasOwnProperty("bar")) // true
like image 198
blackening Avatar answered Oct 23 '25 00:10

blackening



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!