有人可以给我一个关于 TypeScript 和 Angular2 的猴子补丁的例子以及解释吗?
最佳答案
因为 JavaScript 是高度动态的,所以您可以用新成员函数替换任何对象上的成员函数(和相关功能)。它允许您在不更改原始代码的情况下修改一段代码的行为。
这是 TypeScript 中的一个简单示例:
// original code, assume its in some library
interface Foo {
a:number,
b():number
}
var foo:Foo = {a:123,b:function(){return this.a}}
// Monkey patch the function b with a new one
// Allows you to change the behaviour of foo without changing the original code
foo.b = function(){return 456}
更多:猴子修补不仅仅是拦截
当您替换函数但保留原始行为时,这就是函数拦截。是的,您使用猴子修补来进行函数拦截(替换函数),但是调用原始函数并不是猴子修补的要求。
- python 答案 What is monkey patching?(仅替换/覆盖)
同样来自维基百科:https://en.wikipedia.org/wiki/Monkey_patch 一个明显取代原始行为的应用程序:
Replace methods / classes / attributes / functions at runtime, e.g. to stub out a function during testing;
最后,仅仅因为您可以调用原件并不意味着您在猴子修补时必须调用原件。
关于javascript - 什么是关于 TypeScript 的猴子补丁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34888075/