Hi I am quite new to javascript. So I just tried to create a simple object that draws two squares into the canvas. To understand object orientation a bit better I put them in different objects (where drawtest.js is the main). Unfortunately I dont see where my error lies. I have been searching posts on stackoverflow for hours, even the example from my prof looks (similiar) like mine, I don’t see the difference but his version works. In firebug I get an:
testobject.draw is not a function
What did I forgot or made wrong?
“index.html”
<!DOCTYPE html>
<html>
<head>
<title>simple object test</title>
<script src="js/drawtest.js" type="text/javascript"></script>
<script src="js/testobject.js" type="text/javascript"></script>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
</body>
</html>
the testfile “drawtest.js”
window.onload = function(){ init(); };
var canvas;
var context;
function init()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
testobject = new Test(context);
testobject.draw(); //this is where I get testobject.draw is not a function
}
the object “testobject.js”
function Test(context){
this.context = context;
Test.prototype=
{
draw:.
function()
{
this.context.fillStyle = "rgb(200,0,0)";
this.context.fillRect (10, 10, 55, 50);
this.context.fillStyle = "rgba(0, 0, 200, 0.5)";
this.context.fillRect (30, 30, 55, 50);
}
};
}
A few problems:
You have a syntax error:
Remove the dot. The syntax error should have shown up in the JavaScript/error console of whatever browser you’re using. Kick around the menu system of your browser to find its developer tools; you’ll want to get familiar with them. Chrome has quite a good set, recent versions of Firefox have them built in, older versions can use the Firebug plug-in.
It’s best not to replace a constructor function’s
prototype; instead, just add to it:You don’t want to make your
prototypemodifications within the constructor function, move that part outside the constructor function. So theTestfunction and its associated prototype properties becomes: