在内存消耗方面有更好的方法,因为您可以通过prototype
. 这同样适用于函数。
undefined
您可以使用辅助函数来实现这一新设计,该函数仅在所需成员不是默认值或与默认值不同时才复制它们。
此外,作为约定,构造函数以大写字母开头,属性通常为 lowerCamelCased。这些命名约定被广泛使用,我强烈建议您遵循它们。
以下设计用于学习目的,除非您计划有很多实例,否则没有必要。SearchOption
function applyConfig(obj, config, props) {
var i = 0,
len = props.length,
k, v;
for (; i < len; i++) {
if (
config.hasOwnProperty(k = props[i]) && typeof (v = config[k]) !== 'undefined' //ingore undefined values
//let default values be shared between instances
&& v !== obj[k]
) {
obj[k] = v;
}
}
}
function SearchOption(config) {
config = config || {};
//handle all immutable values
applyConfig(this, config, ['word', 'page', 'sort', 'itemsView']);
this.subCategories = config.subCategories || [];
}
SearchOption.prototype = {
constructor: SearchOption,
//keeping default values on the prototype is memory efficient
//since they get shared between instances, however we should only use
//this approach for immutable values.
word: '',
page: 1,
sort: 'desc',
itemsView: 18,
//it's better to have functions on the prototype too
set: function (values) {
//not sure why you were doing searchOptions(...)? It looks very wrong
//since the function will get executed in the global object's context (window)
//note that with the following, we will shadow any default prototype
//values, unlike when we called the constructor.
$.extend(this, values);
}
};
var so1 = new SearchOption(), //share same word
so2 = new SearchOption(), //share same word
so3 = new SearchOption({
word: 'test'
});
console.log('so1:', so1.word, 'so2:', so2.word, 'so3:', so3.word);
console.log(so1);