Skip to content

Instantly share code, notes, and snippets.

@cuipengfei
Last active January 4, 2021 17:05
Show Gist options
  • Select an option

  • Save cuipengfei/7969634 to your computer and use it in GitHub Desktop.

Select an option

Save cuipengfei/7969634 to your computer and use it in GitHub Desktop.
functional js function spies
function Spy(target, method) {
var originalFunction = target[method]
var result = {
count: 0
}
target[method] = function() {
result.count++
return originalFunction.apply(target, arguments)
}
return result
}
module.exports = Spy
function Spy(target, method) {
var result = {count: 0}
var originalMethod = target[method];
target[method] = function () {
result.count = result.count + 1
return originalMethod.apply(target, Array.prototype.slice.call(arguments))
}
return result
}
module.exports = Spy
@sr1998

sr1998 commented Jan 4, 2021

Copy link
Copy Markdown

I have a question. Why use a class to hold the count? Can't we have Spy hold a variable count? Is it because we are returning it? If so, can't we have Spy to be a function that acts as a constructor and contains count as a variable in the class??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment