JavaScript猴子补丁
JavaScript monkey-patching
这段代码是我从JS书中获取的。我不知道应该把什么样的方法作为参数传递给这个函数(m)当我这样做时,它输出undefined:
function trace(o, m) {
var original = o[m]; // Remember original method in the closure.
o[m] = function() { // Now define the new method.
console.log(new Date(), "Entering:", m); // Log message.
var result = original.apply(this, arguments); // Invoke original.
console.log(new Date(), "Exiting:", m); // Log message.
return result; // Return result.
};
}
var a = {
x: 1,
y: 2
};
var plus = function(obj) {
return this.x + this.y;
}
o
为对象,m
为方法名
/**
* Modifies a given object's property by making it log
* the enter/exit times of a method call
* @param {object} o object that has a method that will be called
* @param {string} m name of the method within the given object
*/
function trace(o, m) {
var original = o[m]; // Remember original method in the closure.
o[m] = function() { // Now define the new method.
console.log(new Date(), "Entering:", m); // Log message.
var result = original.apply(this, arguments); // Invoke original.
console.log(new Date(), "Exiting:", m); // Log message.
return result; // Return result.
};
}
var obj = {
doSomething: function() {
console.log('obj.doSomething was called');
}
};
// Won't log enter/exit times
obj.doSomething();
trace(obj, "doSomething");
// Will log enter/exit times
obj.doSomething();
下面是一个例子。
形参o必须是一个对象。第二个参数m是0中方法的名称。跟踪方法替换对象中的方法。新方法增加了一些日志记录并调用被替换的方法。
function trace(o, m) {
var original = o[m]; // Remember original method in the closure.
o[m] = function() { // Now define the new method.
console.log(new Date(), "Entering:", m); // Log message.
var result = original.apply(this, arguments); // Invoke original.
console.log(new Date(), "Exiting:", m); // Log message.
return result; // Return result.
};
}
var a = {x:1, y:2};
var plus = function (obj) {
return this.x + this.y;
}
var test = {
method : plus
}
trace(test, "method");
test.method(a);
相关文章:
- Javascript袖珍参考,第121页:这是怎么回事;猴子补丁”;方法应该有效
- 任何人都知道IE7设置或更新/补丁,它可以防止IE因为jquery错误而无法加载页面
- 了解Javascript中的猴子补丁
- tastypie和x-editable使用补丁
- 补丁'这'带有jQuery的变量
- 使用油脂猴子自动点击延迟
- 猴子补丁导出功能
- 如何在没有临时变量的情况下扩展方法(猴子补丁)
- 在篡改猴子中,变量urlm的行为不同
- 带有篡改猴子错误的 MomentJS
- 你能对YUI模块的猴子补丁方法吗?
- 猴子补丁 jquery 函数内容
- 什么是关于打字稿的猴子补丁
- 如何猴子补丁快速视图查找
- 在GNOME Shell扩展'这是猴子的补丁,这是出乎意料的
- 猴子补丁没有开火.(我猜这只猴子不会打鸭子.)
- 我该如何申报'猴子补丁'打字稿中的原型
- JavaScript猴子补丁
- 是“;猴子补丁”;真的那么糟糕
- 在编写TypeScript单元测试时,我可以对依赖进行猴子补丁吗?