javascript - How to use a variable as constructor property? -


function volkswaggen($options) {    $.each($options, function(k,v) {     this.k = v;   }); } /* ============================== */  var $polo = new volkswaggen({model: "polo", doors: 3});  console.log($polo.model); // << want return "polo" 

$polo.model returns undefined.

if change this.k = v; this[k] = v; , console.log(this.model) inside each loop, console returns "polo undefined" , console.log($polo); still returns undefined.

any ideas?

code screengrab

here's fiddle:
https://jsfiddle.net/jcjwebdesign/zztqyvf4/1/

function volkswaggen($options) {     var self = this;     $.each($options, function(k, v) {         self[k] = v;     });     }  /* =========================================== */  var $polo = new volkswaggen({model: "polo", doors: 3});  console.log($polo.model); 

inside $.each this not newly created object,jquery says -"the keyword refers element."

so should assign this variable. lets self , use instead. , don't have return (self or this), js takes care of that

working fiddle


Comments