Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method I can overload to handle undefined properties in JavaScript? [duplicate]

Tags:

javascript

I'm looking for a way to handle calls to undefined methods and properties in JavaScript.

These would be similar to the PHP magic methods __call, __callStatic, __get.

An example of the code using this might be:

var myObject = {};
myObject.__call = function (called, args) {
    alert(called);
    alert(args);
    return(true);
}

myObject.meow("kitty", "miau");

This would result in the first alert dialog displaying "meow" and the second to display "kitty, miau".

like image 596
Alexander Trauzzi Avatar asked Feb 26 '10 19:02

Alexander Trauzzi


1 Answers

Proxy can do it! Proxy can do EVERYTHING! An answer is given here: Is there a javascript equivalent of python's __getattr__ method? . To rephrase in my own words:

var myObject = new Proxy({},{get(target,name) {
  return function() {
    alert(name)
    console.log(arguments) // alerts are bleh
    return true
  }
}})

myObject.meow("kitty", "miau") // alerts "meow", logs ["kitty","miau"] to the console, and returns true

Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.

like image 154
B T Avatar answered Dec 01 '22 01:12

B T