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は何も返さないため、testPlaneundefinedです。

于 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 に答える