Variable not defined inside ES6 class without 'let' or 'var'

前端 未结 1 1541
南笙
南笙 2021-01-24 01:31

When I use the ES6 class syntax, a variable inside a method declared without \'let\' or \'var\' is undefined. However, when using the regular object syntax, it is defined.

1条回答
  •  -上瘾入骨i
    2021-01-24 01:50

    When I use the ES6 class syntax, a variable inside a method declared without 'let' or 'var' is undefined.

    Actually, it's undeclared. That's why you get an exception.

    However, when using the regular object syntax, it is defined.

    That's because ES6 class methods automatically run in strict mode, your regular object syntax does only run in sloppy mode. (It should not! "use strict" mode everywhere!)
    Assigning to an undeclared identifier will implicitly create a global variable, a thing which you'll definitely want to avoid.

    Not using the class syntax solves this problem

    No, the problem is solved by properly declaring the variable.

    0 讨论(0)
提交回复
热议问题