Reputation: 8523
I'm new to the prototype structure, and I'm having trouble figuring this one out. Here's my JavaScript code.
var Game = function ()
{
//some variables
};
Game.prototype.block =
{
spawn: function () {
var t1 = new this.inst;
},
inst : {
x: 5,
y: 0,
type: ''
}
};
When I try to create a new object "inst" I get the following error: TypeError: object is not a function. What am I doing incorrectly?
Upvotes: 0
Views: 640
Reputation: 48761
If you want to create objects that inherit from the inst
object, you can do that using Object.create
, with var t1 = Object.create(this.inst);
.
var Game = function () {
//some variables
};
Game.prototype.block = {
spawn: function () {
var t1 = Object.create(this.inst);
},
inst : {
x: 5,
y: 0,
type: ''
}
};
So then your code would look something like this;
var game = new Game();
game.block.spawn();
And the .spawn()
method would have a variable that references an object that inherits from the Game.prototype.block.inst
object.
Upvotes: 1
Reputation: 5458
I guest you need a static factory method to create new "inst". is the below code what you need? you call the Game.spawn method to generate a new inst, and you can put this method in setInterval.
function Game() {
//some variables
}
Game.spawn = function() {
function Inst() {
this.x = 5;
this.y = 0;
this.type = '';
}
return new Inst;
}
var inst1 = Game.spawn();
inst1.x = 1; //test inst1
console.log(inst1.x);
var inst2 = Game.spawn();
inst2.x = 2; //test inst2
console.log(inst2.x);
var inst3 = Game.spawn();
inst3.x = 3; //test inst 3
console.log(inst3.x);
Upvotes: 0
Reputation: 4118
First of all, inst
is not defined within the scope of Game
. So, this
which refers to Game
doesn't have any properties called inst
. Secondly, inst
must be followed by ()
to indicate a call to the constructor, which you are missing here.
Upvotes: 0