gpt4 book ai didi

javascript - 对象属性存在但返回未定义?

转载 作者:行者123 更新时间:2023-11-30 18:12:38 25 4
gpt4 key购买 nike

我在脚本中有一个自定义类/对象。在其中一个对象方法中,当我运行以下命令时:

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

我在这里遗漏了什么吗?

更新:我添加了调用代码的函数

最佳答案

只是一个大胆的猜测,但“问题”可能出在 Chrome 控制台上。当您将 this 上下文输出到调试器时,控制台会在检查时显示 current 值,而不是在执行时显示。

Take a look at this fiddle .单击该按钮时,您将在控制台中看到:

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) 代替。

关于javascript - 对象属性存在但返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com