Utilizzando la funzione prototipo di javascript per variabili inizializzazione in 'questo' contesto
-
16-10-2019 - |
Domanda
sto trovando difficile da spiegare a parole, ecco un frammento di codice che sto provando, ma Firefox / Firebug va in tilt!
Sto cercando di seguire questo e questo come guida. Quello che sto cercando di fare qui è
- nuovo MyObject.Method ( 'string', optionsArray);
-
optionsArray articoli sono iterato e salvati utilizzando la funzione di prototipo 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; }
e nel mio html blocco di script pagina, ho
window.onload = function () { var options = [ { property1: { show: true, min: 0, max: 100 } }, { currentValue: { show: true, colour: 'black' } } ]; var myObj = new MyObj.Method('someDivId',options); }
Si prega di avvisare se sto sopra complicare il codice. Penso che il controllo per hasOwnProperty aiuterebbe.
Soluzione
Questo dovrebbe essere un modo più pulito di ottenere ciò che si vuole:
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
Nota: Per quale hasOwnProperty
è di circa consulta qui .
Altri suggerimenti
Ho fatto una dichiarazione per MyObj
e rimosso il nome della funzione initialise
quanto si sta, ovviamente, dichiarando questa funzione per essere una proprietà di MyObj
. Il tuo codice finale sarà quindi come qui di seguito, e che corre per me più che bene. Si noti che è non può in realtà chiamare la funzione fino a quando si dichiara la funzione di prototipo, perché altrimenti l'oggetto avrà alcuna nozione della funzione 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);
questo problema dovrebbe funzionare è hai avuto il tuo myObj = new MyObj ... di fuori il vostro evento onload e opzioni era fuori della sua portata, come è stato dichiarato come variabile privata alla funzione anonima legata al onLoad evento.
Ho risolto anche il modo in cui stava copiando i valori delle proprietà in quanto ha raddoppiato i nomi della proprietà e ne ha fatto un po 'confuso.