我们可以从jsonObject创建实例吗?
Can we create instance from jsonObject?
我需要你的帮助,我的问题是我们可以从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();
相关文章:
- 实例创建(JS)
- 如何基于数组值创建新实例
- 代码挑战:创建一个跟踪对象实例总数的类Foo
- JavaScript:如果现有对象被实例化为具有特定值,如何创建警报
- 用javascript创建另一个对象的实例
- 单击按钮创建多实例jQuery UI对话框
- 如何确定 HTML 元素是使用哪个实例创建的
- 创建一个类,该类使用es6类语法将Function对象创建为实例
- 调用函数和创建函数实例之间的Javascript差异
- setTimeout是否创建函数实例
- 基于分隔符/方括号的实例创建数组
- Ember.js:如何使用模型的单个实例创建路由/控制器
- 从继承的实例创建 JavaScript 基类对象
- 对象的等效实例.创建和原型链
- 这是正常的行为,为每一个Firefox窗口,我的插件的另一个实例创建
- Aurelia自定义元素实例创建
- 为多个实例创建一个jquery代码
- 是否更改构造函数's属性的实例创建后会影响实例吗?如果是,那么如何
- 实例创建
- 烬数据没有为新实例创建id