assignment in javascript and the var keyword

后端 未结 4 662
礼貌的吻别
礼貌的吻别 2020-12-07 02:24

I was reading the \'learning Node\' book and I was stuck in a very simple issue, one that I haven\'t given too much thought about: assignment in javascript.

The auth

4条回答
  •  無奈伤痛
    2020-12-07 02:51

    Just guessing here - this could probably be verified by referring to the ECMAScript 5th Edition spec (but man that thing is a pain) - it probably has to do with the specification of the "var" statement vs assigning attributes to the "global" object.

    When you declare a variable and assign a value to it (var a=2) the returned value is likely "undefined" because that's what the spec says the "var" statement should return.

    When you assign a variable to a symbol without using the "var" statement you are actually assigning a value to an attribute of the global object of that name. That is, a=2 is the same as saying window.a=2 and we know that assinging a value to an attribute returns the value assigned.

提交回复
热议问题