i was using object literal to create an object with methods.
Here a simple example.
var SizeManager = {
width : 800,
height : 600,
ratio : this.width / this.height,
resize : function (newWidth) {
width = newWidth;
height = newWidth / ratio;
}
}
My issue is that SizeManager.ratio returns “NaN“. I’m quite sure it’s an initialization issue.
Is there a way to obtain a correct ratio value?
Is there a way to assign a costructor or initializer to an object literal?
Is defining a constructor objcet the only way?
EDIT: off course SizeManager is ideally a singleton (only one object), that’s way i was using object literal.
Yes, it’s an initialization issue.
thisdoes not refer to yourSizeManagerobject at the point you’re using it. (Object initializers don’t change the value ofthis.)thisis set by how you call a function and has the same value throughout that function call. You’re not calling any function there, sothishas whatever value it had prior to the beginning of that code.(I’ve pointed out something about
ratiofrom your specific example at the very end of this, but first let’s walk through a few options for the general case you raise.)Daniel’s given you a good steer on making
ratioa function except he doesn’t seem to have realized that you want to vary the width. Alternately, ifwidthandheightaren’t going to change, just calculate it afterward:(Side note: I’ve added
this.to the properties you’re referencing inresize. They were missing from your original, but they’re required. Without them, you’re dealing with the horror of implicit globals, which is a Bad Thing(tm).)Of course, you might encapsulate all of that into a factory:
…but then you might as well make it an actual constructor function so you don’t create lots of duplicate (but identical)
resizefunctions:(Note I changed the names a bit on this last one.)
And as one last final note: In your specific example, you don’t actually need to store
ratioat all, you could do this:But that’s just for that specific example, hence the discussion above to talk about the general case.