0

is it possible to get notified each time someone tries to access a specific propoerty of an object in javascript? The code must work in IE 8+ / Firefox and Chrome. I've seen Object.watch but this seems to only be for browsers that support newer Javascript which IE 8 definetly doesn't.

Thanks

Christian
  • 6,961
  • 10
  • 54
  • 82
  • what do you mean, notified ? Like a message in the console or so ? – Laurent S. Apr 08 '14 at 13:50
  • How do you like to be notified? – thefourtheye Apr 08 '14 at 13:50
  • "when someone", who would that be exactly ? – adeneo Apr 08 '14 at 13:50
  • 1
    Can you give a specific example of what you are trying to achieve? In general, you could hide the property in a closure and provide methods to access it. – Matt Burland Apr 08 '14 at 13:51
  • 1
    How about https://gist.github.com/eligrey/384583 (found here: http://stackoverflow.com/a/1270182) – gen_Eric Apr 08 '14 at 13:52
  • 1
    Maybe you are talking about [observer pattern](https://www.google.com.bd/search?q=javascript+observer+pattern&rlz=1C1KMZB_enBD539BD539&oq=javascript+observ&aqs=chrome.1.69i57j0l5.12048j0j7&sourceid=chrome&espv=210&es_sm=122&ie=UTF-8) in `JavaScript` but not sure tho! – The Alpha Apr 08 '14 at 13:53

1 Answers1

1

If you want to do this you can use one of the less-commonly-known features of JavaScript, getters and setters.

function MyObjectClassName (val) {
    this.name = val;
}

MyObjectClassName.prototype = {
    get name() {
        console.log("You just accessed .name!");
        return this.name;
    }
};

var theObject = new MyObjectClassName("James");
var theName = theObject.name;

This example is meant to be self explanatory. When .name appears to be directly accessed on the last line, it will execute the name() function and print to the console.

Be forewarned that this is considered one of the more dangerous features of JavaScript and should not really be used if you expected people to understand your code or have respect for your attention to security (arbitrary code gets executed when the attribute is accessed).

OregonTrail
  • 8,594
  • 7
  • 43
  • 58