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

Tah*_*aza 7 javascript function

I am working on a javascript code where functions are defined in three different ways.

funtion f1(){}
Run Code Online (Sandbox Code Playgroud)

and second

var vaiable = f1(){}
Run Code Online (Sandbox Code Playgroud)

and third

window.f1 = function(){}
Run Code Online (Sandbox Code Playgroud)

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?

Art*_*tem 5

// 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 */ }
Run Code Online (Sandbox Code Playgroud)

如果将第三种方法更改为第二种方法,它将绑定到某个范围(块,它将被放置的位置)。而第三个始终是全局的(可以从任何地方使用)。

请注意,您还可以使用第一种和第二种方法在全局范围内声明函数。例如:

<head>
    <script>function myFunction() {/* body */}</script>
</head>
Run Code Online (Sandbox Code Playgroud)

请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope


luk*_*eli 2

第三个被分配给全局范围(window在浏览器中,global在节点环境中),因此它可以像console对象一样在任何地方访问。