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

Triggering a method of an object that will soon be replaced

本文关键字:对象 方法 替换      更新时间:2023-09-26

给定这个变量:

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

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

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

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

试试这样:

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