I'm trying to learn JavaScript and would appreciate help in understanding why the following won't work. Here is the HTML:
<canvas id="MyCanvas" width="640" height="480"></canvas>
And the JavaScript:
MyCanvas = function (bar) {
this.foo = bar;
}
MyCanvas.prototype = document.getElementById('MyCanvas');
var c = new MyCanvas(20);
alert(c.id);
I would have expected that 'MyCanvas' gets alerted, as I set the prototype to an object where the id attribute has that value. You can check the following fiddle: http://jsfiddle.net/2V9KQ/2/
The problem is that the canvas doesn't have an own id property:
// Setup
var c = document.createElement('canvas');
c.id = "MyCanvas";
// Tests
c.hasOwnProperty('id'); // false
HTMLCanvasElement.prototype.hasOwnProperty('id'); // false
HTMLElement.prototype.hasOwnProperty('id'); // false
Element.prototype.hasOwnProperty('id'); // true
Basically, what happens is that id property is only defined in Element.prototype, and it has a getter and a setter. When you set or get it, the information is stored in or read from an internal property of that Element instance.
But here you are using the property id on a instance of MyCanvas which isn't a true element (although it is an instance of Element). Then, the getter and setter of Element.prototype.id don't work.
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