在函数中定义类是否有效

jel*_*ird 6 javascript ecmascript-6

这个想法或类似的想法在 es6 中可能吗?

function() {
  class A {}
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*dra 7

是的,因为类只是无法调用的函数的语法糖。相反,它必须用 实例化new。您可以使用https://babeljs.io/repl/来查看类的实际情况。

例子

/* ES6 code */
class Car {
  constructor() {
    this.wheels = 4;
  }
}

/* generated ES5 code */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Car = function Car() {
  _classCallCheck(this, Car);

  this.wheels = 4;
};
Run Code Online (Sandbox Code Playgroud)