为什么 JavaScript ES6 不支持多构造函数类? [英] Why doesn't JavaScript ES6 support multi-constructor classes?

查看:23
本文介绍了为什么 JavaScript ES6 不支持多构造函数类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像下面这样编写我的 Javascript 类.

I want to write my Javascript class like below.

class Option {
    constructor() {
        this.autoLoad = false;
    }

    constructor(key, value) {
        this[key] = value;
    }

    constructor(key, value, autoLoad) {
        this[key] = value;
        this.autoLoad = autoLoad || false;
    }
}

我觉得如果我们能这样写出类就好了.预计会发生:

I think it would be nice if we can write out class in this way. Expect to happen:

var option1 = new Option(); // option1 = {autoLoad: false}
var option2 = new Option('foo', 'bar',); // option2 = {foo: 'bar'}
var option3 = new Option('foo', 'bar', false); // option3 = {foo: 'bar', autoLoad: false}

推荐答案

我想像下面这样编写我的 Javascript 类

I want to write my Javascript class like below

你不能,就像你不能重载这样的标准函数一样.您可以做的是使用参数对象查询传递的参数数量:

You can't, in the same way you can't overload standard functions like that. What you can do is use the arguments object to query the number of arguments passed:

class Option {
    constructor(key, value, autoLoad) {
        // new Option()
        if(!arguments.length) {
            this.autoLoad = false;
        }
        // new Option(a, [b, [c]])
        else {
            this[key] = value;
            this.autoLoad = autoLoad || false;
        }
    }
}

Babel REPL 示例

当然(使用您更新的示例),您可以采用不关心参数数量的方法,而是不关心是否传递了每个单独的值,在这种情况下,您可以这样做类似:

Of course (with your updated example), you could take the approach that you don't care about the number of arguments, rather whether each individual value was passed, in which case you could so something like:

class Option {
    constructor(key, value, autoLoad) {
        if(!key) { // Could change this to a strict undefined check
            this.autoLoad = false;
            return;
        }
        this[key] = value;
        this.autoLoad = autoLoad || false;
    }
}

这篇关于为什么 JavaScript ES6 不支持多构造函数类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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