0

I created a Vector3 function on javascript

    function Vector(basex,basey,basez) {
    if(!(this instanceof Vector))
        return new Vector (x,y,z);
    this.x=basex;
    this.y=basey;
    this.z=basez;
}

Vector.prototype.toString=function(){
    return '(' + this.x + ', '+  this.y + ', ' + this.z +   ')';
}


s= new Vector(1,2,3); //(1,2,3)

however, when I try to reassign s with

s=Vector(3,4,5)

I get ReferenceError at line NaN: x is not defined

If I use

 s=new Vector(3,4,5)

It works, but is this the correct way to reassign my variable? I tried to look up the web for some "reassigning my variable" but only fond that a primitive vars can be reassigned

var n=3;
n=5;

But nothing about functions. Any headups?

1
  • (Working with immutable values is usually much easier and safer. I'd go with a single assignment, and no reassignments, in 99% of my code. Just saying.) Commented Feb 15, 2017 at 16:30

1 Answer 1

3

In this code:

if(!(this instanceof Vector))
    return new Vector (x,y,z);

The variables x, y, and z are not defined. You probably meant to use the values which were passed to the function:

if(!(this instanceof Vector))
    return new Vector (basex,basey,basez);
Sign up to request clarification or add additional context in comments.

1 Comment

couldn't feel more dumb than I do now... missed this one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.