How to enter javascript code at the beginning of each prototype method?

I want to enter code in javascript for debugging purposes inside each prototype of my methods in javascript. This example shows only one class, but suppose I have hundreds of classes, and each class has dozens of methods . This mechanism should be performed at the prototype level without the need to indicate the name of each class / method.

function MyClass1() { this.attrib = "ABC"; } MyClass1.prototype.myMethod = function() { alert("first row"); // <---- THE INJECTION SHOULD OCCUR BEFORE THIS LINE OF CODE } 

The idea is to dynamically inject some code before the first line of myMethod () during the first load / execution of javascript code. For instance:

 MyClass1.prototype.myMethod = function() { alert("I was injected dynamically"); alert("first row"); } 

So, for every other class and method, this should happen. Is this possible with the Function.prototype approach?

+4
source share
1 answer

Just wrap your method. Here is the standard method:

 MyClass1.prototype.myMethod = function() { alert("first row"); } 

Then wrap it:

 var orig = MyClass1.prototype.myMethod; MyClass1.prototype.myMethod = function() { alert('Injected'); return orig.apply(this, arguments); } 

You ask two questions, and I answered only one of them (i.e. how to wrap a function). The other part - how to do this on many functions - is best done using a specialized library. In fact, this can be done using Aspect Oriented Programming (AOP) . I found a couple of JavaScript libraries that offer this, one of them is Aop.js (try doing a google search more for yourself).

+9
source

Source: https://habr.com/ru/post/1490033/


All Articles