0

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!"?

bloomers
  • 255
  • 4
  • 12
  • [Related SO question](https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript-or-jquery) – Lincoln Bergeson May 22 '17 at 16:22
  • 2
    @LincolnBergeson the answers to the related question barely mention `Proxy` which is the correct way of doing this now. – Alnitak May 22 '17 at 16:25
  • @Alnitak is there no hope for getters and setters? – Lincoln Bergeson May 22 '17 at 16:28
  • @LincolnBergeson AFAIK there's no way to implement access to (initially) undefined array index properties other than via `Proxy`. Getters and setters only work for properties that you already know about. – Alnitak May 22 '17 at 17:59

1 Answers1

2

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]);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91