使用javascript原型模式,如何设置选项的默认值,然后用指定的参数覆盖这些值?
var myController = function() {
//constructor
}
myController.prototype.options = {
element: '.el',
selector: '.selector'
};
myController.prototype.init = function(args) {
console.log(this.options.element);
console.log(this.options.selector)
};
var params = {
element: '.test'
};
myController.init(params);
应输出
'.test'
'.selector'
因为params.element
应该覆盖options.element
属性。
答案 0 :(得分:2)
这是我希望你会喜欢的解决方案。我是根据你的要求写的。
var myController = function(){
//constructor
}
myController.prototype.options = {
element: '.el',
selector: '.selector',
anotherthing: 'blah',
anotherotherthing: 'blah blah'
};
myController.prototype.init = function(args){
//woah...
//Object.getOwnPropertyNames(object) creates an array of the object's properties
for(var c = 0; c < Object.getOwnPropertyNames(args).length; c++){
//loops through every property of this.options
for(var d = 0; d < Object.getOwnPropertyNames(this.options).length; d++){
//checks if the current property names are equal...
if(Object.getOwnPropertyNames(args)[c] === Object.getOwnPropertyNames(this.options)[d]){
//... and if they are it assigns the value of the args property to the this.options property
this.options[Object.getOwnPropertyNames(args)[c]] = args[Object.getOwnPropertyNames(args)[c]];
}
}
}
}
//and to prove it works
var thing = new myController();
var params = {
element: '.test', //will replace thing.options.element
anotherthing: 'was replaced', //will replace thing.options.anotherthing
something: 'that won\'t do anything' //will do nothing, isn't a property of thing.options
};
thing.init(params);
console.log(thing.options);
运行代码段,然后检查控制台。