在ES6类中没有'let'或'var'的变量未定义 [英] Variable not defined inside ES6 class without 'let' or 'var'

查看:271
本文介绍了在ES6类中没有'let'或'var'的变量未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用ES6类语法时,声明为没有'let'或'var'的方法中的变量是未定义的.但是,在使用常规对象语法时,会对其进行定义.

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.

为说明问题,我在Node v7.5.0上运行以下代码:

To illustrate the problem, I run the following code on Node v7.5.0:

class ES6Foo {

   bar() {  

       var i = 5446;
       console.log("i = " + i);

       let j = 5446;
       console.log("j = " + j);

       k = 5446;
       console.log("k = " + k);

    }
}

foo = new ES6Foo();
foo.bar();

产生输出:

i = 5446
j = 5446
.../ES6Foo.js:10
    k = 5446;
      ^
ReferenceError: k is not defined
at ES6Foo.bar 

不使用类语法可解决此问题:

Not using the class syntax solves this problem:

var OldFoo = function() {}

OldFoo.prototype.bar = function() {

   var i = 5446;
   console.log("i = " + i);

   let j = 5446;
   console.log("j = " + j);

   k = 5446;
   console.log("k = " + k);

}

foo = new OldFoo();
foo.bar();

产生:

i = 5446
j = 5446
k = 5446

任何人都可以解释这种行为吗?

Can anyone explain this behavior?

推荐答案

当我使用ES6类语法时,声明为没有'let'或'var'的方法中的变量是未定义的.

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.

这是因为 ES6类方法自动模式!)
分配给未声明的标识符
将隐式创建一个全局变量,这是您绝对要避免的事情.

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.

这篇关于在ES6类中没有'let'或'var'的变量未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆