constructor - Javascript object literal: value initialization? -
i using object literal create object methods.
 here simple example.
var sizemanager = {     width : 800,     height : 600,     ratio : this.width / this.height,     resize : function (newwidth) {         width = newwidth;         height = newwidth / ratio;     } }   my issue sizemanager.ratio returns "nan". i'm quite sure it's initialization issue.
 there way obtain correct ratio value?
 there way assign costructor or initializer object literal?
 defining constructor objcet way?  
edit: off course sizemanager ideally singleton (only 1 object), that's way using object literal.
yes, it's initialization issue. this not refer sizemanager object @ point you're using it. (object initializers don't change value of this.) this set how call function , has same value throughout function call. you're not calling function there, this has whatever value had prior beginning of code.
(i've pointed out ratio specific example @ end of this, first let's walk through few options general case raise.)
daniel's given you steer on making ratio function except doesn't seem have realized want vary width. alternately, if width , height aren't going change, calculate afterward:
var sizemanager = {     width : 800,     height : 600,     resize : function (newwidth) {         this.width = newwidth;         this.height = newwidth / this.ratio;     } }; sizemanager.ratio = sizemanager.width / sizemanager.height;   (side note: i've added this. properties you're referencing in resize. missing original, they're required. without them, you're dealing horror of implicit globals, bad thing(tm).)
of course, might encapsulate of factory:
function makesizemanager(width, height) {     return {         width : width,         height : height,         ratio : width / height,         resize : function (newwidth) {             this.width = newwidth;             this.height = newwidth / this.ratio;         }     }; } var sizemanager = makesizemanager(800, 600);   ...but might make actual constructor function don't create lots of duplicate (but identical) resize functions:
function sizemanager(width, height) {     this.width = width;     this.height = height;     this.ratio = width / height; } sizemanager.prototype.resize = function (newwidth) {     this.width = newwidth;     this.height = newwidth / this.ratio; }; var asizemanagerinstance = new sizemanager(800, 600);   (note changed names bit on last one.)
and 1 last final note: in specific example, don't need store ratio @ all, this:
var sizemanager = {     width : 800,     height : 600,     resize : function (newwidth) {         var ratio = this.width / this.height;         this.width = newwidth;         this.height = newwidth / ratio;     } };   but that's specific example, hence discussion above talk general case.
Comments
Post a Comment