How do I implement something like pointers in javascript?
I know that javascript doesn't have pointers in terms of a variable referring to a place in memory but what I have is a number of variables which are subject to change and dependent on each other.
For example:
Center (x,y) = (offsetLeft + width/scale , offsetTop + height/scale)
As of now I have rewritten the equation in terms of each individual variable and after any changes I call the appropriate update function.
For example: If scale changes, then then the center, height, and width stay the same. So I call
updateoffset() {
offsetLeft = ce开发者_StackOverflownterx - width/scale;
offsetTop = centery - height/scale;
}
Is this the easiest way to update each of these variables when any of them changes?
I read your question in two different ways, so two answers:
Updating calculated values when other values change
The two usual ways are: 1. To require that the values only be changed via "setter" functions, and then you use that as an opportunity to recalcuate the things that changed, or 2. To require that you use "getter" functions to get the calculated value, which you calculate on the fly (or if that's expensive, you retrieve from a cached calculation).
Returning multiple values from a function
If you're looking for a way of returning multiple values from a single function, you can do that easily by returning an object. Example:
// Definition:
function center(offsetLeft, offsetTop, width, height, scale) {
return {
x: offsetLeft + width/scale,
y: offsetTop + height/scale
};
}
// Use:
var pos = center(100, 120, 10, 20, 2);
// pos.x is now 105
// pos.y is now 130
精彩评论