Last active
October 26, 2016 16:17
-
-
Save chestozo/7788710 to your computer and use it in GitHub Desktop.
Log all calls to some object by wrapping all his methods
This file contains 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
var lw = { | |
wrap: function(type, onlyOwnProperties) { | |
for (var key in type) { | |
if (typeof type[key] === 'function') { | |
if (onlyOwnProperties && !type.hasOwnProperty(key)) { | |
continue; | |
} | |
(function(methodName) { | |
var _method = type[methodName]; | |
type[methodName] = function() { | |
var result = _method.apply(this, arguments); | |
console.log(methodName, arguments, '>>>', result); | |
return result; | |
}; | |
})(key); | |
} | |
} | |
}, | |
// This one works: | |
// - wrap original method | |
// - copy own props from original method to wrapper | |
wrapMethod: function(obj, methodName) { | |
var _method = obj[methodName]; | |
obj[methodName] = function() { | |
var result = _method.apply(obj, arguments); | |
console.log(methodName, arguments, '>>>', result); | |
return result; | |
}; | |
for (var prop in _method) { | |
if (_method.hasOwnProperty(prop)) { | |
obj[methodName][prop] = _method[prop]; | |
} | |
} | |
} | |
}; |
Now we see method output.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
[ ] pass a list of method names to spy for
[ ] show object name in logs
[ ] add support for properties