我正在研究一个项目,目前正在学习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,
});
}
答案 0 :(得分: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
根本不返回任何内容,{ {1}}是testPlane
。
答案 1 :(得分:0)
如果你想使用“jet”函数作为构造函数,你需要用“new”来调用它作为 -
var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
OR
将此行放在“jet”函数中 -
if(!(this instanceof jet)) {
return new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
}
另外..我希望“currentAirport”,“google”在您的代码中定义。