[英]Javascript setter and getter over prototype initialization function
[英]Javascript prototype setter and getter
使用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
屬性。
這是一個解決方案,希望您會喜歡。 我已經按照您的要求寫了。
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);
運行代碼段,然后檢查控制台。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.