覆盖函数通过扩展它并基于条件执行扩展函数

时间:2017-01-19 07:58:35

标签: javascript

我有一个函数,我想覆盖这个函数,然后我想基于几个全局值执行重写函数。

var myName = 'Raju';
function x() {
  console.log(myName);
}

//Now extend the function and based on condition like if myName === 'Raju' alert the name

2 个答案:

答案 0 :(得分:1)

希望这能帮到你!

var myName = 'Raju';
function x() {
  console.log(myName);
}

// overwrite the global function, passing the old function as oldFn
x = (function(oldFn) {
  function extendedFn() {
    oldFn();
    if (myName == 'Raju') {
      alert('hi');
    }
  }
  return extendedFn;
})(x);


x();

答案 1 :(得分:0)

你可以覆盖这样的功能:

var myName = 'Raju';

function x() {
  console.log(myName);
}

var orgX = x;

x = function() {
  console.log('Hello');
  if(myName == 'Raju') {
     orgX();
  }
}  

x();