When we develop some large front-end projects, we have a situation where there is a field on a variable. We want to know which program modifies the field on this variable. For example, on the global variable window, we define a new field, _name, and we want to know which program assigned the value to this field.

It would take too long to debug line by line. Wouldn’t it be convenient to execute a listener of our own when the window _name field is assigned?

The implementation of the listener is simple:

<html>

<script>

"use strict";

function test(){

  Object.defineProperty(window."_name", {

  get : function(){ console.log("gett is called ")},set : function(newValue){

      debugger;

      console.log("_name is filled!!!!");

  },

  enumerable : true.configurable : true

});

for( var i = 0; i < 2; i++)

   console.log(i);

window._name = "2";

};

test();

</script>
Copy the code

DefineProperty is used with Object. The first argument is the Object to listen on, window. The second argument is the name of the Object field to listen on, _name.

The third argument is an object with the property set, which means we want to listen for the event at which window._name is assigned. The value of the set property is a JavaScript function, which is our own defined listener. This listener is raised when window._name is modified by another JavaScript function.

To test this, execute the above code in the browser and find that the breakpoint is triggered as expected:

We can also see from the call stack that the breakpoint was triggered by the line window._name = “2”, and our own registered property change listener did work.

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: