简体   繁体   English

尝试扩展javascript函数时,如何避免过多的递归错误?

[英]How can I avoid too much recursion error when trying to extend a javascript function?

I have a class in javascript with a property that is a function. 我在javascript中有一个带有函数功能的类。 When I try to redefine that function like this: 当我尝试重新定义该函数时,如下所示:

myObject.someBehavior = function()
{
  myObject.someBehavior();
  extraLogic();
};

I am getting a "Too much recursion error". 我收到“太多递归错误”。 I understand why I am getting this error, the myObject.someBehavior is holding a reference to the function, so changing the function does not change the reference. 我了解为什么会收到此错误,myObject.someBehavior持有对该函数的引用,因此更改函数不会更改该引用。 So my question is how can I avoid this? 所以我的问题是如何避免这种情况?

To clarify, I am trying to extend a behavior function of a javascript object. 为了澄清,我正在尝试扩展javascript对象的行为功能。 IN C#, I would just override the method, calling the base class's version first. 在C#中,我只是重写该方法,首先调用基类的版本。 Not sure how to do this in javascript. 不确定如何在javascript中执行此操作。

You could achieve this with closures . 您可以通过闭包来实现。 I'm not sure whether it's a good idea for what you're trying to do though. 我不确定这对您尝试做的事情是否是个好主意。 You might be better off learning how inheritance works in JS . 学习继承在JS中的工作方式可能会更好。

myObject.someBehavior = (function(oldFunction) {
    return function() {
        oldFunction();
        extraLogic();
    };
})(myObject.someBehavior);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM