search

Home  >  Q&A  >  body text

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?

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?

仅有的幸福仅有的幸福2750 days ago944

reply all(7)I'll reply

  • PHP中文网

    PHP中文网2017-06-26 11:00:35

    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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-26 11:00:35

    There is no reason, this is the rule.

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-26 11:00:35

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

    'use strict';
    
    var v = 2;
    console.log(window.v);   // undefined

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-26 11:00:35

    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.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-26 11:00:35

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

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-26 11:00:35

    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.

    reply
    0
  • typecho

    typecho2017-06-26 11:00:35

    Function scope

    reply
    0
  • Cancelreply