Javascript构造函数和对象

时间:2017-05-09 20:50:48

标签: javascript oop object constructor

我需要有一个像这样的边缘对象:

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

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

然而,当我初始化它时,我得到一个错误,说edge不是构造函数。

var a=new Array();

a[0]=0+move; a[1]=200;  
a[2]=0+move; a[3]=130;
var ed=new edge(a,"a");

1 个答案:

答案 0 :(得分:2)

您在同一范围内只能有一个名为edge的标识符。当发生这种情况时,最后一个被分配来覆盖前一个。由于提升,首先处理函数声明(即使它在代码中显示为第二个),然后您的对象将覆盖它。因此,当您到达尝试使用edge作为构造函数的行时,它已被对象覆盖。有关提升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);




相关问题