更改方法的可选参数值时出错

我有一个JavaScript类...


class MyClass{


    static createElement(selector, settings = {

        name : 'element',

        enabled : true,

        color : '#EAEAEA'

    }){

          name = settings.name;

          enabled = settings.enabled;

          color = settings.color;


         // Do something...

    }


    static destroyElement(selector){

        // Do something...

    }


}

使用两种静态方法,一种用于创建元素,另一种用于销毁它们。两种方法都将对象选择器作为第一个参数,而要创建的方法则接收用于对象配置的第二个可选参数。


因此,假定应允许以下配置:


MyClass.createElement(selector); // If you want to create an element with the default settings. (name: 'element', enabled: true and color: '#EAEAEA')


MyClass.createElement(selector, { name : 'element1' }); // A new element is created independent of the previous one but with the same configurations, it only changes the name.


MyClass.createElement(selector, { // Another independent element that changes the name and is deactivated, but that keeps the default color #EAEAEA

    name : 'element2',

    enabled : false

});

问题是什么?如果我创建一个settings默认情况下保留参数的元素,则一切正常,但是如果我创建一个对象并更改其中一个settings参数...


...createElement(selector, { name : 'element1' });

然后其他参数(启用的和颜色的)获取一个值,undefined它们应保留其默认值(true和#EAEAEA),并且仅应更改name


喵喔喔
浏览 149回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript