Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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;
  };
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: message is not working on emit in node.js 
Javascript :: initializing a property asynchronously 2 
Javascript :: everything about fetch 
Javascript :: angular form initialse 
Javascript :: iterate set javascript 
Javascript :: nodejs cors 
Javascript :: js how to find not unic values in array 
Javascript :: remove anything through bubbling 
Javascript :: how to check if .each first element 
Javascript :: get latest journal entry without html 
Javascript :: how to pass parameter in javascript function from html 
Javascript :: Easiest way to create a form data object with Form Selector 
Javascript :: firestore get first document in collection and delete it 
Javascript :: Javascript Reverse Words O(n) time O(1) space 
Javascript :: how to store data in cookie in javascript 
Javascript :: self excuting arrow function 
Javascript :: call function on scroll down javascript 
Javascript :: class validator validate form data 
Javascript :: nextjs update ui when data is updated 
Javascript :: javascript random letters and numbers 
Javascript :: convert low high to integer in js 
Javascript :: Ghost-Blog Maria DB Issue 
Javascript :: Create Own Variable As "Constructor Function" 
Javascript :: _.extend() underscore 
Javascript :: Constructor can also be written like this 
Javascript :: javascript one linde condition 
Javascript :: unreachable code detected javascript 
Javascript :: hsv to rgb js 
Javascript :: javascript online string concatenation 
Javascript :: auto refresh vue pwa 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =