Let’s have the following functionality:
function transformMatrix(a, b, c, d, e, f)
{
this.data = [a, c, e, b, d, f, 0, 0, 1];
}
transformMatrix.prototype.inverse = function()
{
//..
this.data = newdata;
return this.data;
}
and
var m1 = new transformMatrix(1, 0, 0, 1, 10, 20); // translate (10, 20)
Now, when I call
m1.inverse();
variable m1 is changed.
But when I call
var m2 = m1.inverse();
variable m1 is changed and such changed is copied to variable m2. Great!
Is there a way to assign result of inverse to a new variable without change of the original one?
I can do that by:
var m2 = m1;
m2.inverse();
But I would like to know, if there is some other way, without prior assignment, something like
var m2 = {m1}.inverse(); // incorrect syntax
that would not change m1.
Please note that functionality of inverse function should not be changed.
Any help will be appreciated. Thank you…
You need to create a new object from
m1and call theinversefunction on that in order to avoid modifying the original object. Ideally, yourtransformMatrixconstructor would be able to create a new matrix from a matrix that was passed to it. A constructor to do that would look something like this:Now if you pass in an existing matrix to
transformMatrix, it will create a new matrix from the passed in matrix’s data. Modifying the new matrix will not affect the old one. The new syntax would look something like this:m2will now be the reversed version ofm1, andm1will not be affected.Another option: the JSON hack
You have another option that is somewhat hacky, but does not require modifying your original
transformMatrixconstructor: using the JSON hack to duplicate your original matrix and then callingreverse()on the duplicated object. It would look like this:You could even include this hack in your
reverse()function, which would wind up looking like this: