Attaching Functions to an Element Instance

We can modify the DOM element and add its prototype. For example, if we want to add something only to the canvas, we would do something like this:

HTMLCanvasElement.prototype.doSomething = function(arg) { ... }; 

Then we can perform this action for the canvas element:

 var canvas = document.getElementById('canvasId'); canvas.doSomething(...); 

Is it possible to add / attach a function to this canvas instance without changing the prototype HTMLCanvasElement. I just want the canvas where doSomething (...) was called to have access to additional methods, and not to all elements of the canvas in the DOM. How can i do this?

I tried the following in my doSomething function:

 this.prototype.foobar = function() {...} 

However, the prototype is not defined here.

+11
javascript dom html html5 javascript-events
source share
4 answers

Shusl helped me come up with the right answer. It was easier than I thought. In my doSomething (args) function, instead of trying to modify the prototype of the object, I simply bound the function directly. Here is the full source code:

 HTMLCanvasElement.prototype.doSomething = function(args) { this.foobar = function(args) { ... }; } var canvas = document.getElementById('canvasId'); canvas.doSomething(...); canvas.foobar(...); 

Now foobar is only available for the canvas instance where doSomething was called. At the same time, I should not have any instance information.

+10
source share

In this case, you can directly connect a method to your canvas object

 var canvas = document.getElementById('canvasId'); canvas.doSomething= function() {...}; ///doSomething will only be available to this particular canvas. canvas.doSomething(...); 
+5
source share

With jQuery you can use the data property.

 //setting the function $('element').data('doSomething', function(arg) { ... }); //calling the function $('element').data('doSomething')(arg); 

Jsfiddle

+4
source share

Object.defineProperty(element, 'doSomething', {value:function(arg){ ... }} );

Where element 'is the element to which you want to add the property, doSomething is the name, and the third argument is the property of the property itself. In your case, this is a function.

For example:

 var mycanvas = document.createElement("canvas"); Object.defineProperty(mycanvas, 'doSomething', { value: function(x){console.log(x); }, configurable: true }); mycanvas.doSomething('my message'); //prints 'my message' to the console. 

The 'configurable' property indicates whether you want the 'doSomething' property to be able to be changed again after it is created. Check out the details of MDN for more information and examples.

0
source share

All Articles