Becky O Brien
Becky O Brien

Reputation: 69

Maths.js for Vector properties

I have been instructed to make a Maths.js which will have Vector properties such as adding, multiplication, dot product and cross product. Calculating these is fine, but i am new to javascript and i would like a few ideas on how to go about this. Can i make a Vector.js with 3 vars: val1, val2, val3 and pass them through a constructor to another javascript file called Maths.js ? Then in Maths.js do my mathematics ? Then of course in my HTML file make a few buttons once the user enters a value. I have been googling about constructors and getters and setters in javascript and have found this is achievable. Thanks for the help in advance.

This is what i have tried

Vector.js

<script>
var value1 = 0;
var value2 = 0;
var value3 = 0;

function Vector (var val1, var val2, var val3) 
{
    this.value1 = val1;
    this.value2 = val2;
    this.value3 = val3;

}
function getValue1()
{
    return this.value1;
}
function setValue2(val)
{
    this.value1 = val;
}
function getValue2()
{
    return this.value2;
}
function setValue2(val)
{
    this.value2 = val;
}

function getValue3()
{
    return this.value3;
}
function setValue3(val)
{
    this.value3 = val;
}



</script>

Upvotes: 0

Views: 458

Answers (1)

Matt
Matt

Reputation: 20786

You can do this in just one file Math.js:

function Vector(x,y,z) {
    var self = this;
    self.x = x;
    self.y = y;
    self.z = z;
    self.add = function(v) {
        return new Vector(self.x+v.x,self.y+v.y,self.z+v.z); }
    self.minus = function(v) { /*TODO*/ }
    self.dot = function(v) { /*TODO*/ }
    self.cross = function(v) { /*TODO*/ }
}

In your main html file:

var v1 = new Vector(1,2,3);
var v2 = new Vector(4,5,6);
var v3 = v1.add(v2);
...

Upvotes: 1

Related Questions