[英]How to access an object's attributes in Javascript
I am working on a project and currently learning Javascript. 我正在研究一个项目,目前正在学习Javascript。 Right now, I am wondering how I can create an object with a constructor, assign attributes to it, and later read and modify these attributes. 现在,我想知道如何使用构造函数创建对象,为其分配属性,以及稍后读取和修改这些属性。 I think I got the creation and the assigning part right, but I can't seem to access any of my object's attributes from the outside. 我认为我的创作和分配部分是正确的,但我似乎无法从外部访问我的任何对象的属性。
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,
});
}
Check your browser console: 检查浏览器控制台:
TypeError: Cannot read property 'id' of undefined
Use new
to treat jet
as a constructor: 使用new
将jet
作为构造函数处理:
var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
Without new
, the code assigns whatever value jet()
returns to testPlane
, but since jet
does not return anything at all, testPlane
is undefined
. 如果没有new
,代码会分配jet()
返回 testPlane
任何值,但由于jet
根本没有返回任何内容,因此testPlane
undefined
。
If you want to use the function "jet" as constructor, you need to call it with "new" as - 如果你想使用函数“jet”作为构造函数,你需要用“new”来调用它 -
var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
OR 要么
put this line inside function "jet" - 把这条线放在“喷射”功能里面 -
if(!(this instanceof jet)) {
return new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
}
Also.. i hope "currentAirport", "google" are defined in your code. 另外..我希望你的代码中定义“currentAirport”,“google”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.