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

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

问题描述

我要像下面写我的Javascript类。

 类选项{
constructor(){
this.autoLoad = false;
}

构造函数(键,值){
this [key] = value;
}

构造函数(key,value,autoLoad){
this [key] = value;
this.autoLoad = autoLoad ||假;
}
}

我认为如果我们可以写出类这样。
预期发生:

  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}


解决方案>

您不能在同样的方式,你不能重载标准函数那样。您可以做的是使用参数对象查询传递的参数数量:

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

Babel REPL示例



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

  class Option {
constructor(key,value,autoLoad){
if(!key){//可以将此更改为严格未定义检查
this.autoLoad = false;
return;
}
this [key] = value;
this.autoLoad = autoLoad ||假;
}
}


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}

解决方案

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 Example

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天全站免登陆