Question

Je trouve qu'il est difficile d'expliquer avec des mots, voici donc un extrait de code que je essayer mais Firefox / Firebug va dans chute libre!

Je suis en train de suivre cette et cette comme guide. Ce que je suis en train de faire ici est

  1. nouvelle MyObject.Method ( 'string', optionsArray);
  2. Les produits optionsArray sont itérées et sauvegardés à l'aide de la fonction prototype 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;
    }
    

    et dans mon html bloc de script de la page, j'ai

    window.onload = function () {
    
            var options = [
            {    property1: {
                    show: true,
                    min: 0,
                    max: 100
                }
            },
            {
                currentValue: {
                    show: true,
                    colour: 'black'
                }
            }
        ];
    
    var myObj = new MyObj.Method('someDivId',options);
    }
    

S'il vous plaît conseiller si je suis sur ce qui complique le code. Je pense que la vérification des hasOwnProperty serait utile.

Était-ce utile?

La solution

Cela devrait être un moyen plus propre de réaliser ce que vous voulez:

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

Remarque: Pour ce qui est sur le point hasOwnProperty s'il vous plaît voir ici .

Autres conseils

J'ai fait une déclaration pour MyObj et a retiré le nom de la fonction initialise puisque vous déclarez évidemment que cette fonction soit une propriété de MyObj. Votre code final sera alors comme ci-dessous, et qui fonctionne pour moi très bien. S'il vous plaît noter que vous ne peut pas fait appeler la fonction jusqu'à ce que vous déclarez la fonction prototype, car le reste de l'objet aura aucune notion de la fonction 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);
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);

cela devrait fonctionner problème est que vous aviez myObj = new MyObj ... en dehors de votre événement onload et des options était hors de son champ d'application telle qu'elle a été déclarée comme variable privée à la fonction anonyme liée à la événement onload.

Je l'ai fixé aussi la façon dont vous copiait les valeurs des propriétés qu'il a doublé les noms de la propriété et fait un désordre bits.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top