Dou*_*elm 2 javascript node.js ecmascript-6
我有一个JavaScript类,我想使用对象提供默认值.如果没有为某些值提供用户输入,我只希望默认值成为类的一部分.但是,我不知道如何实现这一点.这是我的班级:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
this.term = options.terms;
this.country = options.country;
this.media = options.media;
this.entity = options.entity;
this.attribute = options.attribute;
this.callback = options.callback;
this.limit = options.limit;
this.lang = options.lang;
this.version = options.version;
this.explicit = options.explicit;
this.url = options.url;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的默认值:
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
Run Code Online (Sandbox Code Playgroud)
我意识到这可以通过函数的默认参数来实现,但我宁愿提供一个包含默认值的对象.
执行此操作的典型方法是使用Object.assign()将传入值与默认值合并:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
let opts = Object.assign({}, defaults, options);
this.term = opts.terms;
this.country = opts.country;
this.media = opts.media;
this.entity = opts.entity;
this.attribute = opts.attribute;
this.callback = opts.callback;
this.limit = opts.limit;
this.lang = opts.lang;
this.version = opts.version;
this.explicit = opts.explicit;
this.url = opts.url;
}
}
Run Code Online (Sandbox Code Playgroud)
解释如何Object.assign()在这里工作:
{}作为目标(空对象)开始当然,如果您的实例属性名称与options对象中的属性名称相同,则可以采用更干燥的方式执行此操作,如下所示:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
let opts = Object.assign({}, defaults, options);
// assign options to instance data (using only property names contained
// in defaults object to avoid copying properties we don't want)
Object.keys(defaults).forEach(prop => {
this[prop] = opts[prop];
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1329 次 |
| 最近记录: |