[英]JavaScript prototypes: replace a function
I want to decorate a function of a JavaScript "class" (prototype): 我想装饰一个JavaScript“类”(原型)的功能:
SomeClass = function() { this.someVar = 5; };
SomeClass.prototype = {
foo: function(arg) { /* do something with this.someVar */ }
}
However, I cannot change the source of SomeClass
nor am I able to influence the instance creation of SomeClass
instances. 但是,我无法更改SomeClass
的来源,也无法影响SomeClass
实例的实例创建。
Therefore I thought about doing the following: 因此,我考虑了以下操作:
var oldFoo = SomeClass.prototype.foo;
SomeClass.prototype.foo = function(arg) {
console.log("Yey, decorating!");
oldFoo(arg);
};
This seems to work fine, however, due to function scoping oldFoo
cannot access someVar
anymore (the this
object is now window
). 但是,由于功能范围界定, oldFoo
不能再访问someVar
( this
对象现在是window
),因此,这似乎可以正常工作。 How to overcome this issue? 如何克服这个问题?
You need to delegate it correctly. 您需要正确地委派它。 What's happening is that since you're calling oldFoo
like a bare function the this
value is set to undefined (or the global object in non-strict mode). 发生的情况是,由于您像裸函数一样调用oldFoo
因此this
值设置为undefined(或非严格模式下的全局对象)。
Apply the method with the arguments and set the this
value explicitly: 应用带有参数的方法并显式设置this
值:
oldFoo.apply(this, arguments); // use the same `this` and same arguments as called.
Note that in order to be really correct - you also need to return the result. 请注意,为了真正正确-您还需要返回结果。 So in total your code should look something like: 因此,总的来说,您的代码应类似于:
SomeClass.prototype.foo = function(arg) {
console.log("Yey, decorating!");
return oldFoo.apply(this, arguments); // alternatively capture the return value
}; // and process it and then return it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.