如何知道“谁”执行此功能

时间:2015-09-15 19:49:38

标签: javascript html

在我的Javascript代码中,我有这个

function log_function() {

   console.log("WHO FIRED ME");

}

window.alert = log_function;
window.open = log_function;
window.confirm = log_function;

在函数log_function中我想知道“谁”解雇了“log_function”。可能吗?我将该函数分配给更多函数,因此我想知道是谁解雇了log_function。

例如,如果在页面内有一个类似的脚本:

警报( “AAA”);

我想知道被阻止的“警报”并将其记录在控制台中。

2 个答案:

答案 0 :(得分:1)

您可以使用闭包:

function log_function(caller) {
   return function() {
      console.log(caller + " FIRED ME");
   }
}

window.alert = log_function('alert');
window.open = log_function('open');
window.confirm = log_function('confirm');

答案 1 :(得分:0)

可以修改上下文并传递描述属性:

window.alert = function(){
  var _this = this || {};
  _this.caller = 'window.alert';
  log_function.apply(_this, arguments);
};
window.open = function(){
  var _this = this || {};
  _this.caller = 'window.open';
  log_function.apply(_this, arguments);
};
window.confirm = function(){
  var _this = this || {};
  _this.caller = 'window.confirm';
  log_function.apply(_this, arguments);
};

然后您可以在日志方法中引用this.caller

相关问题