触发即将被替换的对象的方法

时间:2011-12-20 10:41:31

标签: javascript function object hash settimeout

鉴于此var:

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

如果我想劫持它,我会认为我会做类似的事情:

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

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

// 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/