简体   繁体   中英

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.

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

第三个分配给全局范围(浏览器中的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

funtion f1(){} and var vaiable = f1(){} ==> this way your function can be global or local based on whether they are encapsulated in another function.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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