gpt4 book ai didi

javascript - Javascript 中函数(全局)的含义

转载 作者:行者123 更新时间:2023-11-29 18:17:11 25 4
gpt4 key购买 nike

我试图理解function (global) 在下面的代码中的含义,'window' 是传递给函数的参数值或其名称参数而不是参数值?

可能这是使用不常见编码风格的简单 JavaScript。

(function (global) {
var mobileSkin = "",
app = global.app = global.app || {};
app.application = new kendo.mobile.Application(document.body,
{ layout: "tabstrip-layout", skin:"flat"});
})(window);

最佳答案

此代码中有常见的 JavaScript 模式:

  • 命名空间模式。
  • 立即函数模式。

命名空间模式

在浏览器中,窗口对象是全局作用域对象。在您共享的这个代码示例中,程序员创建了一个 immediately-invoked function expression (IIFE) 并将全局对象 window 作为参数传递,在 IIFE 的上下文中绑定(bind)到局部变量 global

顾名思义,该函数会在浏览器解析该文件时立即调用。

从此以后,global只是全局作用域对象window的一个别名,程序员用它来定义一个命名空间app 在里面。

命名空间基本上避免了将全局范围与您需要定义的对象混为一谈,并允许程序员更好地控制在他的自定义范围内定义的内容。

想法是,从现在开始,您应该在此自定义范围内而不是窗口全局范围内定义所有应用程序全局变量,避免与您正在使用的其他第三方库发生名称冲突。这将是其他语言(如 Java 或 C#)中的包或命名空间的伪等价物。

Stoyan Stefanov在他的书中JavaScript Patterns解释如下:

Namespaces help reduce the number of globals required by our programsand at the same time also help avoid naming collisions or excessivename prefixing.

JavaScript doesn’t have namespaces built into the language syntax, butthis is a feature that is quite easy to achieve. Instead of pollutingthe global scope with a lot of functions, objects, and othervariables, you can create one (and ideally only one) global object foryour application or library. Then you can add all the functionality tothat object.

立即调用函数模式

立即调用函数是另一种常见的 JavaScript 模式。它只是一个在定义后立即执行的函数。

Stefanov 描述其重要性如下:

This pattern is useful because it provides a scope sandbox for yourinitialization code. Think about the following common scenario: Yourcode has to perform some setup tasks when the page loads, such asattaching event handlers, creating objects, and so on. All this workneeds to be done only once, so there’s no reason to create a reusablenamed function. But the code also requires some temporary variables,which you won’t need after the initialization phase is complete. Itwould be a bad idea to create all those variables as globals. That’swhy you need an immediate function—to wrap all your code in its localscope and not leak any variables in the global scope:

(function () {
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
today = new Date(),
msg = 'Today is ' + days[today.getDay()] + ', ' + today.getDate();
alert(msg);
}()); // "Today is Fri, 13"

If this code weren’t wrapped in an immediate function, then thevariables days, today, and msg would all be global variables,leftovers from the initialization code.

关于javascript - Javascript 中函数(全局)的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com