Can I extend Vector3 using Javascript?

I made the following function so that a euler angle vector3 will always be in the range -180 to 180 rather than 0 to 360:

function WrapAround( v : Vector3 ) {
    if (v.x >  180) { v.x -= 360; } // wrap around the origin
    if (v.y >  180) { v.y -= 360; } // wrap around the origin
    if (v.z >  180) { v.z -= 360; } // wrap around the origin
    if (v.x <- 180) { v.x += 360; } // wrap around the origin
    if (v.y <- 180) { v.y += 360; } // wrap around the origin
    if (v.z <- 180) { v.z += 360; } // wrap around the origin
    return v;
}

My question is, can I extend the Vector3 class itself? At the moment I call the function like so:

var v3 = Vector3(130,290,210);
var wrappedV3 = WrapAround(v3); // returns (130,-70,-150)

But I would like instead to use:

var v3 = Vector3(130,290,210);
var wrappedV3 = v3.WrapAround; // returns (130,-70,-150)

Is there a way to do this? (In Javascript preferably)

Not possible in JS as far as I can tell (you can't do extension methods as you can't create static classes nor use the correct syntax for the function)

In c#:

public static class ExtensionMethods
{
    public static Vector3 WrapAround(this Vector3 v)
    {
        if (v.x >  180) { v.x -= 360; } // wrap around the origin
        if (v.y >  180) { v.y -= 360; } // wrap around the origin
        if (v.z >  180) { v.z -= 360; } // wrap around the origin
        if (v.x <- 180) { v.x += 360; } // wrap around the origin
        if (v.y <- 180) { v.y += 360; } // wrap around the origin
        if (v.z <- 180) { v.z += 360; } // wrap around the origin
        return v;
    }
}

If you slapped that class in the Assets/Plugins folder, it'd work as is from JS, used like your own example, albeit with the correct syntax for the function :P ( var wrappedV3 = v3.WrapAround(); )

I don’t know about JS in Unity3d, but perhaps you could use prototyping like in normal JS?

You’ll need to do something like this:

Vector3.prototype.constructor = function Vector3(x, y, z)
{
    // from here call the base constructor of Vector3 and then do your 360 modifications afterwards.
}

I’m a little rusty on the specifics, but I’ve done this before. You should be able to Google for it now that you know about prototyping in JS. Either way, if you’re going to write complicated code in JS it’s worth understanding prototyping; it’s how object orientation is achieved in JS.

I do have two questions for you though (out of interest, not necessarily because I know better):

  • Why do you want to do this? There
    must be a reason why Unity3d doesn’t
    work like that and you may run the
    danger of forcing it to work
    differently which will cause other
    problems down the line.
  • Why not use C# instead of JS?