I am trying to add functionality (new methods) to a built-in object (in my case, of type CanvasRenderingContext2D).
The first approach was to add the methods to the prototype, it works, but I would prefer not to modify built-in objects.
I was thinking to use Object.create (from ES5) to extend the object, something like Object.create(context, <my_method_descriptors>)
, however it fails on some browsers when acessing properties/invoking methods on the extended object. For example, this snippet
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext('2d');
var exContext = Object.create(context);
try {
exContext.fillStyle = 'red';
exContext.fillRect(0, 0, 120, 120);
} catch (e) {
alert(e);
}
will fail on IE9 Beta and Safari 5 but succeeds on Firefox 4 Beta and Chrome 7.
Another example: Object.create(new Date()).getDate()
fails in all browsers.
Any thoughts?