我发现很难用语言来解释,所以这是我正在尝试的一段代码,但 Firefox/firebug 进入了混乱状态!
- new MyObject.Method('string',optionsArray);
使用原型函数 Set() 迭代和保存 optionsArray 项
if(typeof(MyObj) == 'undefined') MyObj= {}; MyObj.Method = function initialise(id,options) { this.id = id; this.options = options; this.properties ={}; for (var i = 0; i < this.options.length; i++) // =>options.length=2 (correct) { var obj = this.options[i]; //get the keynames, pass with values to Set() to update properties for (var keys in obj) { console.log(keys); //=> correctly prints 'property1' and 'currentValue' this.Set(keys,obj); //=> this is i guess where it enters a loop? } } } //sets properties MyObj.Method.prototype.Set = function (name, value) { this.properties[name.toLowerCase()] = value; }
在我的 html 页面脚本块中,我有
window.onload = function () { var options = [ { property1: { show: true, min: 0, max: 100 } }, { currentValue: { show: true, colour: 'black' } } ]; var myObj = new MyObj.Method('someDivId',options); }
请告知我是否过度复杂化代码。我认为检查 hasOwnProperty 会有所帮助。