声明 javascript 私有方法

发布于 2025-01-08 05:29:35 字数 888 浏览 0 评论 0原文

可能的重复:
JavaScript:var functionName = function() {} vs function functionName() {}< /a>

在 Javascript 中,“私有方法”基本上只是内部函数。但是在网上提供的各种 javascript 教程中,似乎有两种声明私有方法的做法:

function foo()
{
  var privateMethod = function() { }
}

与...

function foo()
{
  function privateMethod() { }
}

它们似乎都达到了相同的效果,即 privateMethod 不能通过实例公开访问foo。唯一的区别似乎是第一种方式(使用 var 关键字),privateMethod 仅适用于声明之后的代码。但使用第二种方式时,privateMethod 可用于 foo 中的所有代码。那么,是否还有其他差异使得这两种做法更可取呢?

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

In Javascript, "private methods" are basically just inner functions. But throughout the various javascript tutorials available online, there seems to be two practices for declaring private methods:

function foo()
{
  var privateMethod = function() { }
}

versus...

function foo()
{
  function privateMethod() { }
}

They both seem to achieve the same effect, i.e. privateMethod is not accessible publicly through an instance of foo. The only difference seems to be with the first way (using the var keyword), privateMethod is only available to code that comes after the declaration. But with the second way, privateMethod is available to all code within foo. So, is there any other difference that makes either of these two practices preferable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城之時有危險 2025-01-15 05:29:35

还有另一个主要区别:在第一个示例中,函数是匿名的。分配给它的变量有名称,但函数本身没有。当您使用调试器并查看断点列表、调用堆栈等时,这一点很重要。

另一个主要区别是,第一个区别称为函数表达式,发生在执行时点到达代码的该部分,这意味着如果需要,您可以根据逻辑流程为变量分配不同的函数。第二个称为函数声明,仅在其包含范围的顶层有效(不在 if 块、try/catch 内) /code> 等),并在执行进入包含范围时发生(在运行任何分步代码之前)。

您可能很想使用命名函数表达式将两者结合起来:

var foo = function foo() { ... };

......但遗憾的是,尽管它应该有效,但各种 JavaScript 引擎(主要是 Microsoft 的)错误地处理这些内容

There's another major difference: In the first example, the function is anonymous. The variable it's assigned to has a name, but the function itself does not. This matters when you're using the debugger and looking at lists of breakpoints, the call stack, etc.

Another major difference is that the first, which is called a function expression, happens as of when the execution point reaches that part of the code, which means you can assign different functions to the variable depending on the logic flow if you want. The second, which is called a function declaration, is only valid at the top level of its containing scope (not within an if block, a try/catch, etc.), and happens when execute enters that containing scope (before any step-by-step code is run).

You might well be tempted to combine the two, using a named function expression:

var foo = function foo() { ... };

...but sadly although it should be valid, various JavaScript engines (primarily Microsoft's) handle those incorrectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文