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

标签 javascript oop object

我需要你的帮助,我的问题是我们能否从 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/

相关文章:

javascript - 路由器级别订阅中的 meteor 计数

python - 什么是依赖注入(inject)的 Pythonic 方式?

抽象类中的php get_object_vars

python - 字典扩展父类(super class)的完整表示

java - 从文本文档 Java 序列化/反序列化数组列表时出现问题

javascript - ECMAScript/Node : is it possible to save an object instance or context to the filesystem?

java - 想要在 HTML 表单字段中捕获 'Enter' 按键

.net - 领域驱动设计、领域对象、对 Setter 的态度

c# - 对象字典不适用于 JSON

javascript - 使用node-mysql正确处理重复的键