The difference between defining a variable in a function and adding a variable to a function outside the function

:
function foo() {
    var count = 0;
}
console.log(count) //undefined
:
function foo() {
}
foo.count = 0;
console.log(count) // 0

I have tried these two count by myself, and my understanding is that the count in function 1 is a variable defined within the scope of the function, which cannot be accessed outside the function, while in function 2, I also define a variable in the foo, but it can be accessed in the global scope.
what is my misunderstanding, please correct it;
what is the difference between the two count and what is the significance in practical use?

Mar.31,2021

you have found the wrong experimental attribute. There is a count attribute in window, so you can print the value of count. If you are normal, you should report an error

. The understanding of

function one is correct, and the variables defined in the function cannot be accessed outside the function

.

function 2: a function is also an object, and it can also have attributes. The variables in the function, the function attributes, and the global attributes are different

.
function foo() {
    var count = 0; // foo
}
foo.count = 0; // foo
console.log(count) // window

these three count are not the same variable at all


the first count is declared inside the function, called a local variable, and is accessible only in the context of the function's execution.
the second count is not a variable declaration, but assigns a property to the object, the function is also an object in JS, and your foo is equivalent to a global variable, so it can be accessed throughout the global scope.


the former is a variable, which is used to do some calculation within the function. If the function does not execute this variable, it will not be used, and it cannot be accessed directly from the outside. The latter is an attribute for external access.
if it is difficult to understand, treat the former as a private attribute and the latter as a public attribute.

the last sentence console.log (count) is also used incorrectly, which directly accesses the count property of the window object.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e5cf5f-4441a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e5cf5f-4441a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?