使用 javascript 原型(prototype)模式,我如何设置选项的默认值然后用分配的参数覆盖这些值?
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
属性。
最佳答案
这是一个解决方案,希望您会喜欢。我是按照你的要求写的。
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);
运行代码片段,然后检查控制台。
关于Javascript 原型(prototype) setter 和 getter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008616/