使用javascript原型函数初始化'this'上下文中的变量

时间:2011-01-21 13:03:41

标签: javascript-objects prototype-programming javascript

我发现很难用文字解释,所以这里有一段我​​正在尝试的代码,但Firefox / firebug会进入尾声!

我正在尝试关注thisthis作为指导。我在这里要做的是

  1. new MyObject.Method('string',optionsArray);
  2. optionsArray项目使用原型函数Set()

    进行迭代和保存
    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);
    }
    
  3. 请告知我是否过度使代码复杂化。我认为检查hasOwnProperty会有所帮助。

3 个答案:

答案 0 :(得分:3)

这应该是达到你想要的更清洁的方式:

function MyObj(id, options) { // a function that will get used as the constructor
    this.id = id;
    this.options = options;
    this.properties = {};
    this.set(options); // call the set method from the prototype
}

MyObj.prototype.set = function(options) { // set the options here
    for(var i = 0, l = options.length; i < l; i++) {
        var obj = this.options[i];
        for(var key in obj) {
            if (obj.hasOwnProperty(key)) { // this will exclude stuff that's on the prototype chain!
                this.properties[key] = obj[key];
            }
        }
    }
    return this; // return the object for chaining purposes
                 // so one can do FooObj.set([...]).set([...]);
};

var test = new MyObj('simeDivId', [...]); // create a new instance of MyObj
test.set('bla', [...]); // set some additional options

注意:有关hasOwnProperty的内容,请参阅here

答案 1 :(得分:1)

我为MyObj做了声明并删除了函数名initialise,因为您显然声明此函数是MyObj的属性。你的最终代码将如下所示,这对我来说运行得很好。请注意,在声明原型函数之前,不能实际调用该函数,否则该对象将不具有Set函数的概念。

var MyObj = {};

MyObj.Method = function (id,options)
{
    this.id = id;
    this.properties ={};

    for (var i = 0; i < options.length; i++)  // =>options.length=2 (correct)
    {
        var obj = 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?
        }
    }
}

MyObj.Method.prototype.Set = function (name, value) 
{
    this.properties[name.toLowerCase()] = value;
}

var options = [
    {    property1: {
            show: true,
            min: 0,
            max: 100
        }
    },
    {
        currentValue: {
            show: true,
            colour: 'black'
        }
    }
];

var myObj = new MyObj.Method('someDivId',options);

答案 2 :(得分:1)

var MyObj = {};

MyObj.Method = function initialise(id,options) {

    this.id = id;
    this.options = options;
    this.properties = {};

    for (var i = 0; i < this.options.length; i++)
    {
        var obj = this.options[i];  
        for (var keys in obj) {

            this.Set(keys,obj[keys]); 

            //*fix obj => obj[keys] 
            // (and it should be singular key rather then keys

        }
    }

    console.log(this.properties) // will output what you want
}

//sets properties
MyObj.Method.prototype.Set = function (name, value) {
    this.properties[name.toLowerCase()] = value;
}


var options = [{
    property1: {
        show: true,
        min: 0,
        max: 100
    }
},{
    currentValue: {
        show: true,
        colour: 'black'
    }
}];

var myObj = new MyObj.Method('someDivId',options);

这应该工作的问题是你的onload事件之外你的 myObj = new MyObj ... 并且选项超出了它的范围,因为它被声明为绑定到的匿名函数的私有变量onload事件。

我还修复了将值复制到属性的方式,因为它将属性的名称加倍并使其有点混乱。