Reputation: 713
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.
Upvotes: 17
Views: 29492
Reputation: 23208
In that case, you can directly attach 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(...);
Upvotes: 11
Reputation: 41
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.
Upvotes: 3
Reputation: 713
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.
Upvotes: 13
Reputation: 21130
With jQuery, you can use the data
property.
//setting the function
$('element').data('doSomething', function(arg) { ... });
//calling the function
$('element').data('doSomething')(arg);
Upvotes: 8