简体   繁体   English

在另一个匿名函数中嵌入一个匿名函数

[英]Embedding an anonymous function inside of another anonymous function

I have a hash called options. 我有一个叫做options的哈希。 The problem that I'm facing is that options['beforeOpen'] might already be a function, in which case I don't want to overwrite it. 我面临的问题是options['beforeOpen']可能已经是一个函数,在这种情况下,我不想覆盖它。 I'd like to instead call it then call another function that needs to be called every time 我想改为调用它,然后调用每次需要调用的另一个函数

In this example the method that needs to be called every time is methodThatINeedToDo . 在此示例中,每次需要调用的方法是methodThatINeedToDo I thought the code below would accomplish this but it's not working as I expected. 我以为下面的代码可以完成此操作,但是它没有按我预期的那样工作。

function methodThatINeedToDo(){alert('maintenance');}

var options = {beforeOpen: function(){alert('first');}} 
if(typeof options['beforeOpen'] == "function"){
    options['beforeOpen'] = function(){options['beforeOpen'].call(); methodThatINeedToAddToDo();}
} else {
    options['beforeOpen'] = methodThatINeedToDo;
}

The problem is that within the function you're defining to override options['beforeOpen'] , you're using options['beforeOpen'] , which by that time has been overwritten! 问题在于, 您定义的函数中要覆盖options['beforeOpen'] ,而您正在使用options['beforeOpen'] ,到那时该options['beforeOpen']已被覆盖!

You need to cache it and use the cached value within your new function: 您需要缓存它,并在新函数中使用缓存的值:

var cachedBeforeOpen = options.beforeOpen;

if (typeof cachedBeforeOpen == "function") {
  options.beforeOpen = function() {
    cachedBeforeOpen.call();
    methodThatINeedToDo();
  };
} else {
  options.beforeOpen = methodThatINeedToDo;
}

Simply always call methodThatINeedToDo , since you want to and in there check to see if you should call your options method: 只需始终调用methodThatINeedToDo ,因为您要在其中进行检查,看看是否应该调用options方法:

function methodThatINeedToDo(){
  options.beforeOpen && options.beforeOpen();
  alert('maintenance');
}

That really smells like the wrong solution. 这确实闻起来像是错误的解决方案。 Why not Publish/Subscribe pattern ? 为什么不采用发布/订阅模式

Here's a little example: http://jsfiddle.net/ajyQH/ 这是一个小例子: http : //jsfiddle.net/ajyQH/

$(function() {

var yourObj = { yourFct : [] };


$('#btn').click(function() {
    yourObj.yourFct.push(function() {
        $('#testibert').append($('<p>').text('hallo'));
    });
});

$('#btn_exec').click(function() {
    var len = yourObj.yourFct.length;
    for(var i = 0; i < len; i++) {
      yourObj.yourFct[i]();
    }
});
});
var oldCall = options['beforeOpen'];
var newCall = function(){
 oldCall(); 
 methodThatINeedToAddToDo();
};
options['beforeOpen'] = newCall;

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

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