【问题标题】:Triggering a method of an object that will soon be replaced触发即将被替换的对象的方法
【发布时间】:2012-01-24 08:11:15
【问题描述】:

给定这个变量:

somevar = {dothis: function(){console('yay')}};

如果我想劫持它,我想我会做这样的事情:

tempvar = somevar;
somevar = function(){ console.log('yoink'); tempvar();};

但是如果我知道 var 将在 60 秒内重新定义,并且我想在 65 秒内劫持它,我该怎么做? setTimeout 不会立即解析函数,然后引用旧的劫持函数吗?

提前致谢。

【问题讨论】:

    标签: javascript function object hash settimeout


    【解决方案1】:

    试试这样的:

    // initial data
    var somevar = {
      dothis: function(){
        console.log('yay');
      }
    };
    
    somevar.dothis(); // output: yay
    
    // hijacking in 1 second
    setTimeout(function () {
        console.log('hijacking');
        somevar.dothis = (function (orig) {
            return function () {
                console.log('yoink');
                orig.apply(this, arguments);
            };
        }(somevar.dothis));
    }, 1000);
    
    // saved reference running 1.5 seconds later (0.5 seconds after hijacking)
    setTimeout(somevar.dothis, 1500); // output (still): yay
    
    // live reference running 2 seconds later (1 second after hijacking)
    setTimeout(function () {
      somevar.dothis(); // output: yoink / yay
    }, 2000);
    

    演示:http://jsfiddle.net/MDLZt/

    【讨论】:

    • 谢谢 - 你介意解释或发布一个链接来描述这种技术背后的逻辑。我大致理解(或认为)这是引用函数与调用函数的问题,但我很想更深入地掌握它。
    • @Matrym 我不确定您指的是代码的哪一部分。是劫持还是定时调用?关于后者我只能说(因为我自己并不真正知道)setTimeout 似乎会在调用setTimeout 时保存引用。而第二个版本将在可访问范围链中搜索somevar.dothis,从而找到被劫持的。
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多