bloomers
bloomers

Reputation: 265

Is it possible to override certain Javascript commands?

If I created an object that has an array as an attribute, would it be possible to write a method in that object that would make it so that, after an instance is created, that hard-coded commands now acted differently?

For instance, if I defined a constructor:

function Bunny(){
       this.arr = [1,2,3];
       this.doSomething = function(){
         //  do something here
        } 
 }

and then created a new instance:

fluffy = new Bunny();

Would it be possible to write something in "this.doSomething" so that when I perform a predefined command, like:

fluffy.arr[0]=7;

that the resulting action (either in addition to or instead of changing the 0th entry of the array from 1 to 7) is that, say, an alert pops up that says, "Happy Easter!"?

Upvotes: 0

Views: 39

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You can to some degree. Enter: Proxies.

Proxies act as wrappers around objects and allow you to intercept certain events on that objects properties.

let arr = [1, 2, 3];

// Wrap the array in a proxy
arr = new Proxy(arr, {
  get(target, name) {
    // Whenever the user accesses the ith element
    // alert, 'Happy Easter! i'
    alert(`Happy Easter! ${name}`);
    
    // Return the actual value
    return target[name];
  },
  
  // You can also target setters
  set(target, name, value) {
    // Whenever the user sets the ith element
    // alert, 'Merry Christmas! i'
    alert(`Merry Christmas! ${name}`);
    
    target[name] = value;
  }
});

// Can still set values since a setter wasn't set
arr[0] = 7;
console.log(arr[0]);

Upvotes: 2

Related Questions