Prototype

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){
   this.draw{
	this.Circle();
	this.Square();
   }
}

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!!

Hi hiyatran,

There are two problems with your code. First you’re trying to set the prototype of MainMenu before you’ve actually declared MainMenu. Second, this.draw within your MainMenu constructor function should also be a function. The code wants to be something like this:


var MainMenu = function(ctx){
    this.draw = function(){
        this.Circle();
        this.Square();
    }
};
    
MainMenu.prototype = new Shape();

Hi hiyatran,

To get straight into it the following code is never going to work as your declaring the prototype of an undefined variable then declaring it after but not instantiating a new instance of Shape().

MainMenu.prototype = new Shape();

var MainMenu = function([B][COLOR=#ff0000]ctx[/COLOR][/B]){
   [B][COLOR=#ff0000]this.draw{
    this.Circle();
    this.Square();
   }[/COLOR][/B]
}

The following is what’s wrong with this code:

  1. You have declared MainMenu() as a typeofobject” or much fancier a “class” which means you would need to create a new instance of it before you could use it
  2. The variable ctx is within the global context of your script, running the MainMenu() function will cause it to be overwritten in the local scope
  3. this.draw{…} is invalid syntax, in order for this to work an equals “=” sign is required between draw and {

See the below which is your code but updated to work the way you intended it to.

var Shape = function() {}

Shape.prototype.Circle = function() {
    alert('Drawing a circle');
};


Shape.prototype.Square = function() {
    alert('Drawing a square');
};


Shape.prototype.draw = function() {
    this.Circle();
    this.Square();
};


// Create a new instance of the shape class
var MainMenu = new Shape();


// Execute the draw function for "MainMenu"
MainMenu.draw();