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 回答