Javascript 原型(prototype) setter 和 getter

标签 javascript

使用 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/

相关文章:

php - 在ajax、php中显示加载百分比的进度条

javascript - PHPStorm 无法打开 js 文件

javascript - 带有 document.querySelectorAll 的多个选择器

javascript - https 请求基本认证 node.js

javascript - JS : Selecting div's href's and applying the text of href to an input

javascript - javascript 中的关联数组

javascript - Rxjs - 重置 distinctuntilchanged

javascript - Angular 4 如何封装页面结构/路由?

javascript - 找到 k 个数组元素,它们之间的差异最小

javascript - 阅读更多按钮只打开父 div