简体   繁体   中英

Default enum value in javascript class constructor

I have a simple class, and I'm trying to figure out how to set a default value in the constructor:

var Foo = function(bar = Foo.someEnum.VAL1) {

    this.bar = bar;
    someEnum = {VAL1 : 1, VAL2: 2};
}

and to use it like:

var myFoo = new Foo(Foo.someEnum.VAL1);

but this is apparently wrong. What's the correct way to set a default enum value, or do I need to set the default to null, and check for the null in the constructor and set accordingly?

To clarify, bar is an enum for the Foo class. There are other properties in the class that are not shown. Also, updated class code.

You can try this if you want to make bar an optional parameter :

function Foo(bar) {
    this.bar = bar || Foo.enum.VAL1; //If bar is null, set to enum value.
}

//Define static enum on Foo.
Foo.enum = { VAL1: 1, VAL2: 2, VAL3: 3 };

console.log(new Foo().bar); //1
console.log(new Foo(Foo.enum.VAL3).bar); //3

Do you just want bar to be defined inside the function?

var Foo = function() {
    var bar = {VAL1 : 1, VAL2: 2};
}

or for a blank starting object:

var Foo = function() {
    var bar = {};
}

Or are you wanting it to be set from a parameter that's passed into the function?

var Foo = function(barIn) {
    var bar = barIn;
}

Another option - create the object (enum) from values passed in:

var Foo = function(val1, val2) {
    var bar = {VAL1 : val1, VAL2: val2};
}

The possibilities go on, but it's not entirely clear what you're trying to achieve.

I'm not entirely sure what you are trying to do but maybe it is this...

var Foo = function (bar = 1) {
    this.bar = bar;
}
Foo.VAL1 = 1;
Foo.VAL2 = 2;

Now you can do:

foo1 = new Foo();
alert(foo1.bar); //alerts 1;

foo2 = new Foo(Foo.VAL2);
alert(foo1.bar); //alerts 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM