basically all I want to do is be able to call a function referenced in an object, for whatever reason i'm having major trouble, the error on chrome is : Uncaught TypeError: obj.draw is not a functionrender @ main.js:46main @ main.js:16
maybe this means it's private? I'm not sure, anyway's here's a MVCE
var bullets = [];
bullets.push(bullet)
;(function() // I know this is a little overkill for an mvce
{
function main()
{
window.requestAnimationFrame( main );
render();
}
main();
})();
function bullet()
{
this.x = canvas.width/2;
this.y = canvas.height/2;
this.move = function()
{
++this.y;
};
this.draw = function()
{
ctx.beginPath();
ctx.rect(this.x, this.y, 5, 10);
ctx.closePath();
ctx.stroke();
};
}
function render()
{
for( let obj of bullets )
obj.draw();
}
You are pushing a class, but invoking an object's function. Here bullet
is a class and not an instantiation of it. Only the instantiated variables will have the function. Change your code to:
bullets.push(new bullet());
And put the function declaration to the top. (Not necessary).
var bullets = [];
bullets.push(new bullet())
;(function() // I know this is a little overkill for an mvce
{
function main()
{
window.requestAnimationFrame( main );
render();
}
main();
})();
function bullet()
{
this.x = canvas.width/2;
this.y = canvas.height/2;
this.move = function()
{
++this.y;
};
this.draw = function()
{
ctx.beginPath();
ctx.rect(this.x, this.y, 5, 10);
ctx.closePath();
ctx.stroke();
};
}
function render()
{
for( let obj of bullets )
obj.draw();
}
The above code throws canvas
isn't defined, which is expected for the snippet. Hope this helps.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments