可以访问匿名函数的内容吗?

huangapple go评论64阅读模式
英文:

Is it possible to access contents of anonymous functions

问题

可以我访问匿名函数中的变量、对象和函数吗?

我需要访问包含函数的对象。我只需要一个函数,再次调用它。但是这段代码位于匿名函数内部。我不能从那里运行,因为这样可以避免与页面上的各种 JavaScript 产生冲突。

还有其他方法吗?

英文:

It's a very brief question. Is it possible for me to access variables, objects, functions that are inside an anonymous function?

I need to access an object that contains functions. I need only one function, call it again. But this code is inside an anonymous function. I can't run from there, because the reason is not to have conflicts with the various js that are on the page.

And there?

答案1

得分: 1

在 JavaScript 中模块变得常见之前,通过将匿名函数的输出赋值给全局变量来实现你所询问的操作并不罕见。通过一个单一的全局变量来公开其中的方法和属性被认为是一种良好的做法。这样做仍然存在冲突的可能性,但是使用单一全局变量的情况要少得多。

const myAnonFunction = (() => {
  function a() {
    // ...
  }
  function b() {
    a();
    // ...
  }
  function c() {
    // ...
  }

  return {
    b,
    c,
  }
})();

在上面的代码中,我们创建了一个匿名函数并立即执行它,注意最后一行的 ()。函数的输出被赋值给全局常量 myAnonFunction。然后,你可以在外部访问返回语句中的任何内容,比如 myAnonFunction.b()myAnonFunction.c(),但无法访问 .a(),因为它没有被返回。

英文:

Before modules became common in JavaScript it was not uncommon to do what you're asking by assigning the output of an anonymous function to a global variable. One single global variable that has methods and properties made available through it is considered a good practice. There's still the chance for conflicts, but a lot less with a single global variable.

const myAnonFunction = (() => {
  function a() {
    // ...
  }
  function b() {
    a();
    // ...
  }
  function c() {
    // ...
  }


  return {
   b,
   c,
  }
})();

In the above code we create an anonymous function and immediately execute it, note the () on the last line. The output of the function is assigned to the global constant myAnonFunction. You can then access anything that is in the return statement externally such as myAnonFunction.b() and myAnonFunction.c(), but you will be unable to access .a() because it is not returned.

huangapple
  • 本文由 发表于 2023年2月7日 02:52:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定