0

我正在做一个项目,目前正在学习 Javascript。现在,我想知道如何使用构造函数创建对象,为其分配属性,然后读取和修改这些属性。我想我的创建和分配部分是正确的,但我似乎无法从外部访问我的对象的任何属性。

function initialize() { 
    var testPlane = jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

    alert("Never get to this point: " + testPlane.id);
}


function jet(id, from, to, expected, status) {
    this.id = id;
    this.from = from;
    this.to = to;
    this.expected = expected;
    this.status = status;
    this.position = from;
    alert("Id: "+ id + " From:" + from + " To: " + to + " Expected: " + expected + " Status: " + status);
    this.marker = new google.maps.Marker({
      position : this.position,
      icon : img,
      map : map,
    });
}
4

2 回答 2

2

检查您的浏览器控制台:

TypeError: Cannot read property 'id' of undefined

用作new构造jet函数:

var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

如果没有new,代码会将jet() 返回的任何值分配给testPlane,但由于jet根本不返回任何值,所以testPlaneis undefined

于 2013-07-04T19:19:26.067 回答
0

如果你想使用函数“jet”作为构造函数,你需要用“new”来调用它——

var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

或者

将此行放在函数“jet”中 -

if(!(this instanceof jet)) {
    return new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
}

另外.. 我希望在您的代码中定义“currentAirport”、“google”。

于 2013-07-04T19:33:17.350 回答