Horje
how to do something before every method is run in a class javascript Code Example
how to do something before every method is run in a class javascript
// we iterate over all method names
Object.getOwnPropertyNames(Foo.prototype).forEach((name) => {

  // First to do: we save the original method. Adding it to prototype
  // is a good idea, we keep 'method1' as '_method1' and so on
  Foo.prototype['_' + name] = Foo.prototype[name];

  // Next, we replace the original method with one that does the logging
  // before and after method execution. 
  Foo.prototype[name] = function() {

    // all arguments that the method receives are in the 'arguments' object
    console.log(`Method call: method1(${Object.values(arguments).join(', ')})`);

    // now we call the original method, _method1, on this with all arguments we received
    // this is probably the most confusing line of code here ;)
    // (I never user this['method'] before - but it works)
    const result = this['_' + name](...arguments);

    // here is the post-execution logging
    console.log(`Method result: ${result}`);

    // and we need to return the original result of the method
    return result;
  };
});




Javascript

Related
ajax returning html instead of json Code Example ajax returning html instead of json Code Example
shortcut to format reactjs visual studio Code Example shortcut to format reactjs visual studio Code Example
React Rendering Movies Code Example React Rendering Movies Code Example
create table using jade Code Example create table using jade Code Example
fetch image from cloudinary in nodejs Code Example fetch image from cloudinary in nodejs Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
6