Javascript ES6 类默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31342290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:33:31  来源:igfitidea点击:

ES6 Classes Default Value

javascriptecmascript-6babeljs

提问by Leonardo Alves

Is it possible to create a ES6 class, that assigns a default value to a property if it's not passed in the new method?

是否可以创建一个 ES6 类,如果它没有在新方法中传递,它会为属性分配一个默认值?

class myClass {
    constructor(options) {
        this.a = typeof options.a !== 'undefined' ? options.a : 'default a value';
        this.b = typeof options.b !== 'undefined' ? options.b : 'default b value';
        this.c = typeof options.c !== 'undefined' ? options.c : 'default c value';
    }
}

var myClassWithValue = new myClass({a:'a value', b: 'b value'});

If I try to do this with this code, compiling with babeljs, I get a TypeError: Cannot set property 'c' of undefined.

如果我尝试使用此代码执行此操作,并使用 babeljs 进行编译,则会收到 TypeError: Cannot set property 'c' of undefined。

Maybe I am not getting how classes work in javascript.

也许我不明白类在 javascript 中是如何工作的。

回答by Jaromanda X

If you're going to use ES6, why not use all of ES6, i.e. default values for parameters and destructuring assignment

如果你打算使用 ES6,为什么不使用所有的 ES6,即参数和解构赋值的默认值

class myClass {
  constructor({a = 'default a value', b = 'default b value', c = 'default c value'} = {a:'default option a', b:'default option b', c:'default option c'}) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
}
var v = new myClass({a:'a value', b: 'b value'});
console.log(v.toSource());
var w = new myClass();
console.log(w.toSource());

http://www.es6fiddle.net/ibxq6qcx/

http://www.es6fiddle.net/ibxq6qcx/

edit: also tested and confirmed to run on https://babeljs.io/repl/

编辑:还测试并确认可以在https://babeljs.io/repl/上运行

回答by aleha

Object.assignworks for me as well

Object.assign 也适用于我

class RenderProperties {
   constructor(options = {}){
        Object.assign(this, {
            fill : false, 
            fillStyle : 'rgba(0, 255, 0, 0.5)',
            lineWidth : 1,
            strokeStyle : '#00FF00'
        }, options);
    }
}

回答by Mathieu Dutour

I would suggest the following:

我建议如下:

class myClass {
  constructor(options) {
    const defaults = {
      a: 'default a value',
      b: 'default b value',
      c: 'default c value'
    };
    const populated = Object.assign(defaults, options);
    for (const key in populated) {
      if (populated.hasOwnProperty(key)) {
        this[key] = populated[key];
      }
    }
  }
}

var myClassWithValue = new myClass({a:'a value', b: 'b value'});

回答by Cerbrus

TypeError: Cannot set property 'c' of undefined.

类型错误:无法设置未定义的属性“c”。

This means optionsis undefined.

这意味着options未定义。

Make sure the optionsobject exists, first:

首先确保options对象存在:

if(options){
    this.a = typeof options.a !== 'undefined' ? options.a : 'default a value';
    this.b = typeof options.b !== 'undefined' ? options.b : 'default b value';
    this.c = typeof options.c !== 'undefined' ? options.c : 'default c value';
}else{
    this.a = 'default a value';
    this.b = 'default b value';
    this.c = 'default c value';
}

Or, nice and short:

或者,又好又短:

options = options || {};
this.a = typeof options.a !== 'undefined' ? options.a : 'default a value';
this.b = typeof options.b !== 'undefined' ? options.b : 'default b value';
this.c = typeof options.c !== 'undefined' ? options.c : 'default c value';

回答by AESTHETICS

Shorter and cleaner version based on Default parameters from MDN web docs.

基于MDN 网络文档中的默认参数的更短更清晰的版本

class myClass {
  constructor(
  a = 'default a value',
  b = 'default b value',
  c = 'default c value'
  ) {
      this.a = a;
      this.b = b;
      this.c = c;
    }
}

let myClassWithValue = new myClass('a value','b value');

console.log(myClassWithValue);

With passing an Object.

通过传递一个对象。

class myClass {
  constructor({
  a = 'default a value',
  b = 'default b value',
  c = 'default c value'
  }) {
      this.a = a;
      this.b = b;
      this.c = c;
    }
}

let options = {
  a: 'a value',
  b: 'b value'
}

let myClassWithValue = new myClass(options);

console.log(myClassWithValue);

回答by Lucas Breitembach

if there is no parameter passing through the constructor, it is assigned a default value as it was pre-set, I hope I have helped!

如果没有参数通过构造函数,它会被分配一个默认值,因为它是预设的,希望对我有所帮助!

class User {
  constructor(fullName = "fooName", lastName, canAccess = false) {
    this.fullName = fullName;
    this.lastName = lastName;
    this.canAccess = canAccess;
  }
}

回答by Nikola Mitic

If you would like to have some properties default but some not you can use also use spread operator (work as same as Object.assign answer)

如果你想有一些属性默认但有些不是,你也可以使用扩展运算符(与 Object.assign 答案相同)

const defaults = {someDefault: true};

class SomeClass {
    constructor(config) {
        this.config = {...defaults, ...config};
    }
}

回答by sergo911

I made a small correction: Replaced the large object with Object()

我做了一个小更正:将大对象替换为 Object()

class SomeClass {
  constructor({a = 'defA', b = 'defB', c = 'defC'} = Object()) { 
    this.a = a;
    this.b = b;
    this.c = c; }
}
console.log(new SomeClass ({a:'a', b:'b', c:'c'}))
console.log(new SomeClass ({a:'a', c:'c'}))

(Node REPL) Output:

(节点 REPL)输出:

SomeClass { a: 'a', b: 'b', c: 'c' }
SomeClass { a: 'a', b: 'defB', c: 'c' }

回答by Gustavo Rizzo Albuquerque

I build this. I think it is the easiest way to read the code in this problem.

我建这个。我认为这是阅读此问题中代码的最简单方法。

class myClass {

    constructor(options){

        let default_values ={
            a: '',
            b: '',
            c: ''
        }
        options = {...default_values, ...options}

        this.a = options.a;
        this.b = options.b;
        this.c = options.c;
    }
}

回答by rich remer

I'd just add it to the prototype. ES6 classes are just syntactic sugar, so you can use all the standard prototypal inheritance techniques that were available before the introduction of the classkeyword.

我只是将它添加到原型中。ES6 类只是语法糖,因此您可以使用在引入class关键字之前可用的所有标准原型继承技术。

const {assign, seal} = Object;

class MyClass {
    constructor(options) {
        assign(seal(this), options);
    }
}

assign(MyClass.prototype, {
    a: "default a value",
    b: "default b value",
    c: "default c value"
});