search

Home  >  Q&A  >  body text

What is the difference between var, const, let, window.prop and Object.defineProperty?

Please explain the reason for the following example:

<script>
  var a = 1
  let b = 2
  const c = 3
  window.d = 4
  Object.defineProperty(window, 'e', {
    value: 5
  })
  console.log(a, b, c, d, e)
  console.log(window.a, window.b, window.c, window.d, window.e)
</script>
输出:
1,2,3,4,5
1 undefined undefined 4 5
<script>
  Object.defineProperty(window, 'a', {
    value: 1,
    writable: false
  })
  let a = 2
  console.log(a)
  console.log(window.a)
</script>
输出:
2
1
<script>
  Object.defineProperty(window, 'a', {
    value: 1
  })
</script>
<script>
  let a = 2
  console.log(a)
</script>
<script>
  console.log(a)
</script>
输出:
Uncaught SyntaxError: Identifier 'a' has already been declared
1
我想大声告诉你我想大声告诉你2709 days ago828

reply all(2)I'll reply

  • 代言

    代言2017-06-28 09:30:46

    let has independent scope

    const declares a read-only constant. Once declared, the value of the constant cannot be changed.

    Global var will be assigned to window, (this may be what you don’t want)

    It is a very common practice to assign values ​​to the window attribute, but the assignment object is window

    Object.defineProperty can set the setter and getter methods,
    or make it unmodifiable, or even prevent it from becoming an enumeration of objects

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-28 09:30:46

    The Global level in js is the window object. So a can be accessed on the window, and d can also be accessed if it is directly assigned on the window. e is also tied to the window.

    let and const belong to ES2015. Together with them, there is a block-level scope, which means that what they define will only be in the current block-level scope and will not be accessed elsewhere.

    Then the last prompt was occupied, I think it can be explained like this

    reply
    0
  • Cancelreply