1

スクリプトにカスタム クラス/オブジェクトがあります。オブジェクト メソッドの 1 つで、次のコマンドを実行すると:

MapLabel.prototype.show = function()
{
    console.log(this);         // Here are the
    console.log(this.canvas);  // lines in question

    if (!this.canvas) // this is not giving the expected result
    {
        console.log('canvas doesnt exist to show');
        return;
    }

    console.log('showing maplabel');
    this.visible = true;

    this.canvas.style['visibility'] = 'visible';
    this.marker.setVisible(true);
}

私は以下を取得します:

MapLabel {gm_accessors_: Object, fontFamily: "'Droid Sans', 'Helvetica Neue', 
Helvetica, Arial, sans-serif", gm_bindings_: Object, fontSize: 14, fontColor: "#FFFFFF"…}
__e3_: Object
align: "center"
canvas: <canvas>
fontColor: "#FFFFFF"
fontFamily: "'Droid Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif"
fontSize: 14
gm_accessors_: Object
gm_bindings_: Object
gm_props_: Hu
id: 216
map: xh
marker: Ah
markerImage: Qh.MarkerImage
minZoom: 5
position: Q
strokeColor: "#000000"
strokeWeight: 4
text: "Sometext"
visible: false
zIndex: 100
__proto__: Dh

undefined    // <---- this.canvas = undefined even though it exists?

存在し、値を持つ出力を確認できthis.canvasます。しかし、console.log(this.canvas)直後に を実行すると、 が返されますundefined

私がここに欠けているものはありますか?

更新:コードが呼び出されている関数を追加しました

4

1 に答える 1

2

ただの大げさな推測ですが、「問題」はChromeコンソールにある可能性があります。thisコンテキストをデバッガーに出力すると、コンソールには、実行時ではなく、検査時に現在の値が表示されます。

このフィドルを見てください。ボタンをクリックすると、コンソールに次のように表示されます。

The current value is: {"hello":"world"} 
The this context is > Thing {hello: "world"} 
changing value of this.hello... 
The current value is: {"hello":"Cleveland"}

次に、の前にある矢印をクリックしてオブジェクトインスペクターを開くと、次の> Thing {hello: "world"}ように表示されます。

The current value is: {"hello":"world"} 
The this context is  Thing {hello: "world"}
  hello: "Cleveland"                              <-- Surprise!
  test: function () {
  __proto__: Thing
changing value of this.hello... 
The current value is: {"hello":"Cleveland"}

この場合、実行時にthis.canvas実際には未定義です。

念のため、代わりにできconsole.log(this.canvas)ます。

于 2013-01-06T22:35:03.960 に答える