0

I need to have an edge object like that :

var edge={ coordinates:[],  name};

function edge(coordinates,name)
{
this.coordinates = coordinates;
this.name = name;
}

However when I initialize it, I get an error saying edge is not a constructor.

var a=new Array();

a[0]=0+move; a[1]=200;  
a[2]=0+move; a[3]=130;
var ed=new edge(a,"a");
3
  • You're trying to have two different things named edge. If you want a constructor, get rid of the object. function edge... not var edge = {... Commented May 9, 2017 at 20:52
  • You should not have the same name for object and function, try changing name and it will work. Commented May 9, 2017 at 20:53
  • ...and the reason same named object beats the same named function is because function declarations get hoisted to the top of the file. Commented May 9, 2017 at 20:55

1 Answer 1

2

You can only have one identifier named edge in the same scope. When that happens the last one that is assigned to overwrites the earlier one. Because of hoisting, the function declaration is being processed first (even though it appears second in the code) and then your object is overwriting that. So when you get to the line that attempts to use edge as a constructor, it has already been overwritten by an object. See more on hoisting here.

function edge(coordinates, name){
  this.coordinates = coordinates;
  this.name = name;
}

var move = 100; // dummy variable just to make your code work

// Array literal notation. Simpler than making new array and populating
// indexes separately
var a = [0 + move, 200, 0 + move, 130 ];

// Use function as constructor
var e1 = new edge(a, "a");

console.log(e1);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.