We can modify a DOM element and add to its prototype. For example, if we want to add something only to the canvas, we'd do something like this:
HTMLCanvasElement.prototype.doSomething = function(arg) { ... };
We can then perform this action on a canvas element:
var canvas = document.getElementById('canvasId');
canvas.doSomething(...);
Is it possible to add/attach a function to this instance of the canvas without modifying the prototype of HTMLCanvasElement. I only want a canvas where doSomething(...) was called to have access to the additional methods, not all canvas elements in the DOM. How can I do this?
I've tried the following in my doSomething function:
this.prototype.foobar = function() {...}
However, prototype is undefined here.
Shusl helped me come up with the correct answer. It was easier than I thought. In my doSomething(args) function, instead of trying to modify the object prototype, I just directly attached the function. Here's 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 accessible to the instance of the canvas where doSomething was called. At the same time, I don't have to have any information about the instance.
In that case you can directly attache 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(...);
With jQuery, you can use the data
property.
//setting the function
$('element').data('doSomething', function(arg) { ... });
//calling the function
$('element').data('doSomething')(arg);
JSFiddle
Object.defineProperty(element, 'doSomething', {value:function(arg){ ... }} );
Where 'element' is the element you want to add the property to, 'doSomething' is the name and the third argument is an object of the property its self. In your case 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 specifies if you would like the 'doSomething' property to be able to be changed again after it is created. Check out the MDN Details for more information and examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With