Table of contents
Using proxy you can intercept the fundamental functions for objects.
Ever wanted to add an event listener or callback whenever a specific function or value from an object is called? Maybe you are doing recursion and want to check how many times the function is called without passing any extra param. Or want to add a log when someone is running a function or accessing the value from an object.
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 the number of times properties of obj are 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 a 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 a number of time function fibonacci
was called.
That's all for now. Hope you have learned something new today from this article.