When JavaScript declares a variable in the global object, it will become a property of the same name of the global object, but when it is declared in a function, it will not. Why?
仅有的幸福
仅有的幸福 2017-06-26 10:58:35
0
7
864

In JavaScript, after a global variable is declared globally, it will become a property of the global object with the same name. However, after a local variable is declared in a function, it will not become an attribute of the function (object). Instead, it must be declared using "function name.attribute name". What is the reason?

仅有的幸福
仅有的幸福

reply all(7)
洪涛

It can be understood like this:

Variables declared inside a function belong to the function execution context object, not the function object
Variables declared in the global environment belong to the global execution context object, and this context object is the global environment object

我想大声告诉你

There is no reason, this is the rule.

巴扎黑

Historical issues, it is recommended to use strict mode to eliminate confusion.

'use strict';

var v = 2;
console.log(window.v);   // undefined
大家讲道理

If you mean this
`function test(){

var a = 1;     // 你说的a是test的属性。
    this.a = 1;// 这才是函数的属性,因为在JS里,“万物”皆对象(可能夸张了。)
              //如果,还不明白,请自觉翻阅,“神奇的this”,"作用域"等基础JS章节

}`
//Update, error correction.
The questioner has a good look at the basics.

我想大声告诉你

I think this is the scope problem of function variables. js is very flexible. I hope we can learn together^~^ ^~^

淡淡烟草味

In JavaScript, after a global variable is declared globally, it will become a property of the global object with the same name. After a local variable is declared in a function, it becomes a local object, which is an attribute of the function, so you must first access the function globally and then access the local variables in the function.

typecho

Function scope

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!