gpt4 book ai didi

javascript - 我们可以从 jsonObject 创建实例吗?

转载 作者:行者123 更新时间:2023-11-29 16:12:48 27 4
gpt4 key购买 nike

我需要你的帮助,我的问题是我们能否从 JsonObject 创建一个实例。

例如,错误的流动代码结果

var player_hand =
{
x: null,
y: null,
height: null,
width: null,
style: null,
set: function(x, y, width, height, style)
{
this.x= x;
this.y= y;
this.width = width;
this.height= height;
this.style= style;

},
draw: function()
{
DrawRect.draw(this.x, this.y, this.width, this.height , this.style);
}
};
var DrawRect =
{
draw: function(x, y, width, height, style)
{
gameContext.fillStyle = style;
gameContext.fillRect(x, y, width, height);
}
};

var left_hand = new player_hand(); // error.

我知道我的代码中的最后一行会导致错误,但我们可以做类似的事情吗?

最佳答案

player_hand 已经是一个 Javascript 对象,不是构造函数。

你需要做这样的事情。

function player_hand(...) 
{
this.x = null;
// ...
}

然后

var left_hand = new player_hand();

应该可以正常工作。

关于javascript - 我们可以从 jsonObject 创建实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23608589/

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