var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
只需通过prototype:
(function(_old) {
UserMock.prototype.isValid = function() {
// my spy stuff
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
}
})(UserMock.prototype.isValid);
说明:
(function(_old) {
和
})(UserMock.prototype.isValid);
将方法isValue 引用到变量_old。进行了闭包,因此我们不会将父作用域与变量混合。
UserMock.prototype.isValid = function() {
重新声明原型方法
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
调用旧方法并从中返回结果。
使用 apply 可以将所有参数放入正确的范围 (this) 并传递给函数
例如。如果我们创建一个简单的函数并应用它。
function a(a, b, c) {
console.log(this, a, b, c);
}
//a.apply(scope, args[]);
a.apply({a: 1}, [1, 2, 3]);
a(); // {a: 1}, 1, 2, 3