Javascript 添加另一个js文件中存在的方法的事件侦听器

Javascript 添加另一个js文件中存在的方法的事件侦听器,javascript,jquery,html,d3.js,Javascript,Jquery,Html,D3.js,我正在访问另一个js文件中编写的几个方法。所以我是这样访问它们的: 文件1: function minit() { this.addval = function(val1, val2) { return val1 + val2; } function autoexecute(d) { //do something here// //raise event// } }; var con = new minit(); var result = con.ad

我正在访问另一个js文件中编写的几个方法。所以我是这样访问它们的:

文件1:

function minit() {
  this.addval = function(val1, val2) {
    return val1 + val2;
  }

  function autoexecute(d) {
    //do something here//
    //raise event//
  }
};
var con = new minit();
var result = con.addval(2, 3);

/*
con.autoexecute(function(d) { //Wanna do something like this
  alert(d);
});
*/
文件2:

function minit() {
  this.addval = function(val1, val2) {
    return val1 + val2;
  }

  function autoexecute(d) {
    //do something here//
    //raise event//
  }
};
var con = new minit();
var result = con.addval(2, 3);

/*
con.autoexecute(function(d) { //Wanna do something like this
  alert(d);
});
*/
以上各项工作如期进行,取得了良好的效果。。 现在,假设
autoexecute(d)
方法在一段时间间隔后自动调用。我如何知道该方法是否已执行

因此,我想创建一个
autoexecute(d)
(在文件1中)的事件(在文件2中)

更新: 我希望这个例子能帮助你理解这个问题

company.js//这是将在ui.html中用作参考的主文件

ui.html

<script src="company.js"></script>
<script>
  $(document).ready(function() {
    function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//

      alert("comany.js -> hello function is executed");
    }
  });
</script>

$(文档).ready(函数(){
函数bye(personame){//如果调用hello方法,将自动调用此方法。……personame是从hello方法传递的参数//
警报(“comany.js->hello函数已执行”);
}
});

只有在函数具有相同作用域时才能执行此操作(全局作用域是最佳情况)。如果autoexecute函数具有本地作用域,则无法执行

本质上,像这样重写原始函数

// keep a reference to the original function
var _autoexecute = autoexecute;

// override the original function with your new one
function autoexecute(d) {
    alert("before autoexecute");  // fired before the original autoexecute
    _autoexecute(d);              // call the original autoexecute function
    alert("after autoexecute");   // fired after the original autoexecute
}

现在,无论何时调用
autoctexecute
,它都会调用新函数,该函数既可以处理事件前后,也可以调用原始函数。只需删除(可怕的)警报,并根据需要替换为事件处理程序。

据我所知,如果我错了,应该有人纠正我,没有办法(至少没有库)检测javascript中启动的函数。函数执行不会触发其他函数可以“处理”的事件

在您的示例中,您希望一个函数在另一个函数启动后自动启动,您所需要做的就是在第一个“启动”的函数的末尾调用要启动的函数。困惑,但希望这有帮助

function handler(){
  alert("main function was fired!");
}
function main(){
  //Code of main goes here and then at the end just add:
  handler();
}
现在,当您的“main”完成其工作时,它将调用
处理程序
函数


无论您在何处定义处理程序函数(可以是不同的文件或相同的文件),只要可以从
main
的作用域中访问该函数,它都将在其末尾激发。它甚至可以在声明main之后声明,只要它是在启动main之前声明的。

@DavidM没有触发器,就没有事件。以前引用旧autoexecute的同一作用域中的任何函数现在都引用新的。谢谢Archer!但是如何在file2中获取_autoexecute的触发器呢?自动执行是全局函数。。。现在,如何在文件2中获取它的调用触发器?由于autoexecute(d)位于文件1.内,因此这些文件不相关。范围才是最重要的。你试过这个吗?试着让它更清楚地理解。请检查我是否更新了主线程。。我读过了。如果它位于hello方法所在的同一个文件中,那么bye将是fire。但它们不在同一个文件中。。。这就是问题所在。hello()由comany.js内的计时器自动触发。只要Bye声明在同一范围内,而不是文件中,那么它就完全不相关。如果Bye是一个全局函数,它将100%触发