简体   繁体   English

在javascript中,window.function(){}和var variable = function有什么区别?

[英]In javascript, what is the difference between window.function(){} and var variable = function?

I am working on a javascript code where functions are defined in three different ways. 我正在研究以三种不同方式定义功能的javascript代码。

funtion f1(){}

and second 第二

var vaiable = f1(){}

and third 第三

window.f1 = function(){}

I have read about the first two here but don't know about the last one. 我已经在这里阅读了有关前两个的信息,但不了解最后一个。

Will there be a problem if I change the third one to the second one? 如果我将第三个更改为第二个,会不会有问题?

What are the pros and cons of third type? 第三类的优缺点是什么?

Why it is used particularly? 为什么特别使用它?

// this is function declaration in JavaScript
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
function myFunction (/* args */) { /* body */ }

// this is function expression
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
const/var/let myFunction = function myFunction(/* args */) { /* body */ }

// this is basically (unnamed) function expression, defining property `f1` on global object `window`
window.f1 = function (/* args */) { /* body */ }

If you change the third approach to the second one, it will become bound to some scope (the block, where it's going to be put). 如果将第三种方法更改为第二种方法,它将被绑定到某个范围(将放置该块的位置)。 While the third one is always global (it is available from anywhere). 尽管第三个始终是全局的(可在任何地方使用)。

Note that you can also declare function in the global scope, using 1st and 2nd approaches. 请注意,您还可以使用第一种和第二种方法在全局范围内声明函数。 For example: 例如:

<head>
    <script>function myFunction() {/* body */}</script>
</head>

Please, look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope 请查看https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope

第三个分配给全局范围(浏览器中的window ,Node环境中的global ),因此可以在任何地方访问,例如console对象。

window.f1 = function(){} ==> since you are attaching it to window, it will explicitly make your function global and accessible from everywhere window.f1 = function(){} ==>由于您将其附加到窗口,因此它将显式地使您的函数成为全局函数,并且可以从任何地方访问

funtion f1(){} and var vaiable = f1(){} ==> this way your function can be global or local based on whether they are encapsulated in another function. funtion f1(){}var vaiable = f1(){} ==>这样,根据您的函数是否封装在另一个函数中,它可以是全局函数或局部函数。

All of the three stated function declaration/expressions will produce global function as well. 所有三个声明的函数声明/表达式也将产生全局函数。 But be aware of the third function expression: 但是请注意第三个函数表达式:

window.f1 = function(){};

which works well in browser but will throw an error in other environments like Node due to the difference of global object. 可以在浏览器中很好地工作,但由于全局对象的差异,在其他环境(例如Node)中会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM