2011-01-21 3 views
0

Je trouve difficile d'expliquer les mots, alors voici un extrait de code que j'essaie, mais Firefox/firebug va dans le sens inverse! Je suis en train de suivre this et this comme guide. Ce que j'essaie de faire ici estUtilisation de la fonction prototype javascript pour initialiser la variable dans le contexte 'this'

  1. new MyObject.Method ('chaîne', optionsArray);
  2. articles de optionsArray sont réitérés et enregistrés en utilisant 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 ma page html bloc de script, 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 trop compliquer le code. Je pense que la vérification de hasOwnProperty aiderait.

+1

Il est presque impossible de dire ce que vous essayez de faire ici. Ce code n'a vraiment pas beaucoup de sens. La fonction "Set" est sur l'objet prototype pour quelque chose appelé "Gauge.Speedometer" et n'aura donc rien à voir avec "MyObj" ou "MyObj.Method". – Pointy

+0

@Pointy, corrigé. – Abhijit

+1

vous appelez 'MyObj.Method' avant que le tableau' options' ne soit initialisé ou même déclaré, était-ce intentionnel ou juste une faute de frappe? – roryf

Répondre

3

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 

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

+0

+1 pour le conseil de chaînage: D – fedxc

1

J'ai fait une déclaration pour MyObj et j'ai supprimé le nom de la fonction initialise puisque vous déclarez évidemment que cette fonction est une propriété de MyObj. Votre code final sera alors comme ci-dessous, et cela fonctionne bien pour moi. Veuillez noter que vous ne pouvez pas appeler réellement la fonction qu'après avoir déclaré la fonction de prototype car sinon l'objet n'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); 
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); 

cela devrait fonctionner problème est que vous aviez votre 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 à l'événement onload.

J'ai également corrigé la façon dont vous copiiez les valeurs dans les propriétés car elle doublait les noms de la propriété et la rendait un peu compliquée.

Questions connexes