ES6:没有new关键字的调用类构造函数 [英] ES6: call class constructor without new keyword

查看:321
本文介绍了ES6:没有new关键字的调用类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个简单的类

class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}

可以调用类构造函数, code> new 关键字?

Is it possible to call the class constructor without the new keyword?

使用应允许

(new Foo("world")).hello(); // "hello world"

Foo("world").hello();       // "hello world"

但是后者失败了

Cannot call a class as a function


推荐答案

类具有类体,是构造函数

如果使用内部< c $ c> constructor()函数,该函数将是相同的类体,并且将在类被调用时被调用,因此一个类总是一个构造函数。

Classes have a "class body" that is a constructor.
If you use an internal constructor() function, that function would be the same class body as well, and would be what is called when the class is called, hence a class is always a constructor.

构造函数需要使用 new 运算符来创建一个新实例,因为这样调用不带 new 运算符会导致错误,因为类构造函数需要 创建新实例。

Constructors requires the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.

错误消息也非常具体,并且正确

The error message is also quite specific, and correct


TypeError:无法在没有'new'的情况下调用类构造函数

TypeError: Class constructors cannot be invoked without 'new'

您可以;


  • 使用常规函数
  • either use a regular function instead of a class1.
  • Always call the class with new.
  • Call the class inside a wrapping regular function, always using new, that way you get the benefits of classes, but the wrapping function can still be called with and without the new operator2.

1)

function Foo(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
    this.hello = function() {
        return this.x;
    }
}

2) p>

2)

class Foo {
    constructor(x) {
        this.x = x;
    }
    hello() {
        return `hello ${this.x}`;
    }
}

var _old = Foo;
Foo = function(...args) { return new _old(...args) };

这篇关于ES6:没有new关键字的调用类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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