Proxy in javascript. Advance JS
1 min readApr 11, 2022
Using proxy you can intercept the fundamental functions for objects.
What are fundamental functions?
When you do myObject.anyKey
it will invoke get
function and when you do
myObject.anyOtherKey = "Some Value"
you are invoking set
function.
All functions that you can intercept are mentioned here
How you can intercept ?
let obj = {hello:'world'}let proxyObj= new Proxy( obj, {
get: function( target, key, context ) { // you are intercepting get now return "SOMETHING ELSE"
}
});console.log(proxyObj.hello) // SOMETHING ELSE
console.log(obj.hello) // world
But if you want to keep default behaviour and also count number of times properties of obj is accessed.
let obj = {hello:'world'}
let coundObjPropertiesUsed = 0let proxyObj= new Proxy( obj, {
get: function( target, key, context ) {
// you are intercepting get now
coundObjPropertiesUsed++ return target[key]
}
});console.log(proxyObj.hello) // world
console.log(obj.hello) // world
console.log(coundObjPropertiesUsed) // 1
target is the object Proxy is called upon. ( in this case obj)
What is the use case?
- You can use it in logging
- to get how many times function is called
let fibonacci = n => n <= 1 ? n :fibonacci( n - 1 ) + fibonacci( n - 2 );let fibCalls = 0;fibonacci = new Proxy( fibonacci, {
apply: function( target, thisValue, args ) {
fibCalls += 1;
return target(...args);
}});
fibonacci( 12 );
console.log( 'fibCalls:', fibCalls );
above fibCalls
will contain number of time function fibonacci
was called.
Thats all for now. Hope you have learn something new today from this article.