javascript - OOP set a passed-in variable with new data from inside closure? -
when using oop can pass in options link var outside object/closure, can set inside object/closure?
var object = function (element, options) { this.$element = $(element); this.options = { // option1 place: {}, }; // option2 this.place; this.init(); }; object.prototype = { set: function(newplace){ // option1 this.options.place = newplace; //option 2 this.place = newplace; } } $.fn.object = function (option) { if(option instanceof object) { this._object = new object(this, option); return this; }else if(option instanceof string){ switch (option) { // option2 case 'place': return this._object.place; break; default: return this; } } }; $.fn.object.constructor = object;
-------- goal -----------
var newplace = null; var newobject = new object({ place : newplace }); // or $('#').object({ place: newplace }); newobject.set('test'); newplace === 'test'; // <-- object should able set value of external var.
i have tried 2 ways both don't return new data set inside closure/object.
i have labeled them option1 , option2 above.
basically expect var overridden, i've tried playing call/apply.
so turns out may have been trying that's not right way it.
best way , solution pass in function callback in options update local var.
exampleobject = function(options){ options = { update: function(){} } } exampleobject.prototype = { set: function(newplace){ this.options.update(newplace); } } newobject = exampleobject({ update: function(r){ newplace = r; } });
Comments
Post a Comment