简体   繁体   中英

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?

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");

您可以使用lib https://github.com/Olical/EventEmitter并扩展Object.prototype来在每次创建对象时发出事件,并为您设置事件警报。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM