View Full Version : Using Prototype

05-28-2013, 03:26 AM
Here's my code:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var Shape = function(){}

Shape.prototype.Circle = function(){
// Some code here

Shape.prototype.Square = function(){
// Some code here

MainMenu.prototype = new Shape();

var MainMenu = function(ctx){

What I want to do is to call the Circle() and Square() function inside my draw() function.
But it doesn't work.
Is this even possible??
I'm going crazy trying to figure this out!!

05-28-2013, 04:14 AM
In short it or something like it can be done. However there are some problems.

this.draw is not a function unless it's a native function of either a canvas with context, or of a canvas' context. Even if it is either of those, this.draw{ . . . is not a function call. It's an object declaration.

And here:

MainMenu.prototype = new Shape();

MainMenu is not defined yet, so you cannot assign it a prototype yet.

If MainMenu were already a function then you could do that, or something like it. I'm not sure if that exact syntax would be valid or not. In any case, MainMenu would have to be a function before that, or at least an object. A more usual syntax is:

var mainMenu = new Shape();

If you did that, then you could do:

function draw(){


Here's a slightly different approach which shows two ways of initializing to the prototype:

<!DOCTYPE html>
<title>Prototype Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

// Prototype Demo Script (c)2013 John Davenport Scheuer
// as first seen in http://www.dynamicdrive.com/forums/
// username: jscheuer1 - This Notice Must Remain for Legal Use

function Person(props){
props = props || {};
for (var p in props){
this[p] = props[p];

Person.prototype = {
writeName: function(){
this.el().appendChild(document.createTextNode('Hello, my name is ' + this.name + '. '));
el: function(){
return document.getElementById(this.id);
writeSex: function(){
this.el().appendChild(document.createTextNode("I'm a " + this.sex + '.'));
writeMe: function(){
this.el().innerHTML = '';

var aGirl = new Person({
name: 'Sally',
sex: 'girl',
id: 'div1'

var aMan = new Person();
aMan.name = 'Robert';
aMan.sex = 'man';
aMan.id = 'div2';

<input type="button" value="Write Sally" onclick="aGirl.writeMe();">
<div id="div1">aGirl will be written here.</div>
<input type="button" value="Write Bob" onclick="aMan.writeMe();">
<div id="div2">aMan will be written here.</div>