1

I need a way to add new methods to the existing one on some DOM elements (in my case, canvas). I want to do something like this :

var c= document.getElementById('myCanvas');
c.foo = function(){
  console.log('foo' + this.id);
}
c.bar = function(){
  console.log('bar' + this.id);
}

Because it will be used for several canvas elements I don't want to write this code each time.

I could use a method that add this methods to all of my elements, but I was wondering if there is a way to do this with OOP (inheritance ?).

Could I do something like this ?

var extendedCanvas = function(){
  this.foo = function(){
    console.log('foo' + this.id);
  };
  this.bar = function(){
    console.log('bar' + this.id);
  }
}
var c= document.getElementById('myCanvas');
c.prototype = new extendedCanvas();
c.foo();
Michael Berkowski
  • 260,803
  • 45
  • 432
  • 377
ylerjen
  • 3,902
  • 2
  • 23
  • 40

4 Answers4

3
var c= document.getElementById('myCanvas');
c.prototype = new extendedCanvas();
c.foo();

Nope, assigning anything to the .prototype property of an instance does not have any effect. You could add your methods to HTMLCanvasElement.prototype, but extending the native DOM is considered a bad practise.

Instead, try the mixin pattern:

var c= document.getElementById('myCanvas');
extendedCanvas.call(c); // give properties .foo and .bar to 'c' instance
c.foo();
Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
0

Try adding your functions directly onto the Element object like this :

Element.prototype.foo = function() {
    console.log('foo' + this.id);
}
Element.prototype.bar = function(){
    console.log('bar' + this.id);
}
Serge K.
  • 5,143
  • 20
  • 27
0

no, if classA wants to be inherited from classB, prototype of ClassA must be set by an instance of classB....

function classB()
{
    this.Name = "";
}
classB.prototype.func = function(){};

function classA()
{
}
classA.prototype = new classB();

now Name and func are on every instance of classA

and if you want more things on classA you can then do this:

function classA()
{
    this.Family = "";
}
classA.prototype = new classB();
classA.prototype.func_new = function(){};

Family and func_new are only on every instance of classA not classB

Amir Sherafatian
  • 2,085
  • 2
  • 19
  • 32
0

you can use this approach to extend canvas... something like decorator pattern:

    function DecoratedCanvas(id) {

        this.Canvas = document.getElementById(id);

        this.foo = function () { console.log('foo' + this.Canvas.id); };
        this.bar = function () { console.log('bar' + this.Canvas.id); }
    };

    var o = new DecoratedCanvas("myCanvas");
    o.foo();
    o.bar();
    var c = o.Canvas;
Amir Sherafatian
  • 2,085
  • 2
  • 19
  • 32