Last active
January 4, 2021 17:05
-
-
Save cuipengfei/7969634 to your computer and use it in GitHub Desktop.
functional js function spies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
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
why is slice not needed?????