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

Can we create instance from jsonObject?

本文关键字:实例 创建 jsonObject 我们      更新时间:2023-09-26

我需要你的帮助,我的问题是我们可以从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();

试试这个:

var player_hand = function(){
    return {
        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 left_hand = player_hand();

严格地说,如果你愿意告诉Internet Explorer 8及以下的浏览器该去哪里…你实际上可以使用你的player_hand"定义"作为Object.create方法的原型。

简化的例子:

var foo = {
    val: null,
    getVal: function(){ 
        return this.val; 
    }
},
bar = Object.create(foo, {
    val: { value: 'foo' }
});
console.log( bar.getVal() ); // 'foo'

在javascript中,当你用new Something()创建一个对象时,Something指的是一个函数。

如果你想创建从player_hand对象继承的实例,你需要声明一个函数,比如player_hand()(惯例是用大写字母开始构造函数名),并将其原型设置为player_hand:

function Player_hand() {}
Player_hand.prototype = player_hand;

你现在可以写:

var left_hand = new Player_hand();