Home > Back-end >  Override a specified method of an object with new functionality while still maintaining all of the o
Override a specified method of an object with new functionality while still maintaining all of the o

Time:10-01

Is it possible to create a Spy function that returns an object that keeps track of how many times a function is called like shown below?

var spy = Spy(console, 'error')

console.error('calling console.error')
console.error('calling console.error')
console.error('calling console.error')

console.log(spy.count) // 3

CodePudding user response:

You could wrap the call to the method

class Spy {
  constructor(obj, method) {
    this.count = 0

    const _method = obj[method] // save the ref to the original method
    const self = this

    // wrap the method call with additional logic
    obj[method] = function () {
      self.count  
      _method.call(this, ...arguments)
    }
  }
}

var spy = new Spy(console, "error")

console.error("calling console.error")
console.error("calling console.error")
console.error("calling console.error")

console.log(spy.count) // 3

CodePudding user response:

you can use javascript Clouser property.

// Initiate counter
let counter = 0;

// Function to increment counter
function add() {
  counter  = 1;
}

// Call add() 3 times
add();
add();
add();

// The counter should now be 3

reference https://www.w3schools.com/js/js_function_closures.asp

  • Related