user4277027
user4277027

Reputation:

JavaScript: how to create an alert if an existing object is instantiated with a specific value?

(This is just for personal curiosity)

I would like to setup an automatic alert when-ever one of the built-in JavaScript objects (meaning: objects that I have not defined myself) is instantiated with a specific value.

So here is for example a non-built-in object called "Test":

function Test(first, last) {
   this.firstName = first;
   this.lastName = last;
}

One of the things I have tried with is adding a self-executing function named "checkName" to the "Test" object, like so:

Test.prototype.checkName = function() {
   var n = this.firstName;
   if (n == "Mickey") {
      alert("It's Mickey!!");
   }
}();

However instantiating this as follows does not result in an alert:

var a = new Test("Mickey", "Mouse");

Is it possible to augment existing objects so as to create an automatic alert when a property has some specific value?

If it is, how can this be done?

Upvotes: 0

Views: 160

Answers (3)

Tamas Hegedus
Tamas Hegedus

Reputation: 29906

You cannot modify existing constructors, but you can replace them. The following code will alert on instantiations, and the replaced constructors will yield the same objects like before:

var _Set = Set;

Set = function() {
  var args = Array.prototype.slice.call(arguments, 0);
  alert(JSON.stringify(args));
  return new (Function.prototype.bind.apply(_Set, [null].concat(args)));
};

new Set("kenyér"); // alerts ["kenyér"]

However you cannot expect any library to function properly after this, for example the instanceof operator no longer works:

new Set() instanceof Set  // will return false
new Set() instanceof _Set // will return true

Upvotes: 0

Caio Fontes
Caio Fontes

Reputation: 2143

You could use a lib https://github.com/Olical/EventEmitter and extend Object.prototype to emit an event each time a object is created and make the event alert for you.

Upvotes: 0

Oriol
Oriol

Reputation: 288080

JavaScript can't read your mind. You must call the method manually.

And it must be a method, not an immediately invoked function expression. When you call it like that this becomes the global object in sloppy mode or unrefined in strict mode. So this.firstName will either be window.firstName or throw an exception.

function Test(first, last) {
  this.firstName = first;
  this.lastName = last;
  this.checkName();
}
Test.prototype.checkName = function() {
  var n = this.firstName;
  if (n == "Mickey") {
    alert("It's Mickey!!");
  }
};
var a = new Test("Mickey", "Mouse");

Upvotes: 0

Related Questions