如何以编程方式替换(包装)新方法中的方法?
我有几个方法需要以基本相同的方式包装在新方法中。 我的第一个解决方案不起作用,我明白为什么,但我不知道是否有一个简单的解决方案可以解决这个问题,或者是否不能按照我想要的方式完成。
这是一个例子。 我有对象 ac 具有 onClick 方法。 我需要在 onClick 方法之前执行一些代码。 我尝试了以下方法:
// objects a-c
a = {onClick : function () { console.log('a'); }};
b = {onClick : function () { console.log('b'); }};
c = {onClick : function () { console.log('c'); }};
// first try
var arr = [a, b, c]
for (var i = 0; i < arr.length; i++) {
var oldOnClick = arr[i].onClick;
arr[i].onClick = function () {
// new code here
oldOnClick();
}
}
// outputs 'c'
// what i want is to maintain a reference to the original method
// so in this case, execute my new code and output 'a'
a.onClick();
这不起作用,因为当调用新方法时,oldOnClick将指向上次迭代中的方法,而不是分配时的to方法。
有没有一个我忽略的简单解决方案?
I have several methods that I need to wrap in new methods in basically the same manner. My first solution doesn't work, and I understand why, but I don't know if there is a simple solution to this problem or if it can't be done the way that I want to do it.
Here's an example. I have objects a-c that have an onClick method. I need to execute some code before the onClick methods. I tried the following:
// objects a-c
a = {onClick : function () { console.log('a'); }};
b = {onClick : function () { console.log('b'); }};
c = {onClick : function () { console.log('c'); }};
// first try
var arr = [a, b, c]
for (var i = 0; i < arr.length; i++) {
var oldOnClick = arr[i].onClick;
arr[i].onClick = function () {
// new code here
oldOnClick();
}
}
// outputs 'c'
// what i want is to maintain a reference to the original method
// so in this case, execute my new code and output 'a'
a.onClick();
This doesn't work because when the new method is called, oldOnClick will point to the method from the last iteration and not the to method when it was assigned.
Is there a simple solution that I'm overlooking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你需要的是关闭:
What you need is closure:
您是否尝试过使用 Javascript 的 AOP 框架?
例如使用 jQuery AOP 插件:
另请检查此处。
did you tried with some AOP framwork for Javascript?
for example using jQuery AOP plugin:
check also here.
Javascript 绑定规则非常奇怪。 确实,JavaScript 很奇怪。
我不知道我会将此称为修复它的方法,但是通过引入子函数,您可以引入另一个绑定,从而解决这个特定问题。
您的(针对快速 Chrome 黑客攻击而修改的)代码变为:
上面的代码抛出三个警报:a、b、c。 任何替换“//新代码”的内容都将在正确的时间运行。
Javascript binding rules are pretty odd. Really, javascript is pretty odd.
I don't know that I'd call this the way to fix it, but by introducing a sub-function you can get introduce another bind and thereby fix this particular problem.
Your (modified for quick-y Chrome hacking) code becomes:
The above code throws up three alerts: a, b, c. Anything replacing '//New Code' will be run at the right time.