Im trying to extend the HTMLElement using TypeScript. Below is my code which alerts undefined because "this" returns a window object, which seems right. How can I access the calling HTMLElement in a similar fashion?
interface HTMLElement {
setData(dataObject: any): void;
}
HTMLElement.prototype.setData = (dataObject: any) => {
alert(this.id); //Undefined
alert(this); //Window Object
}
var data = { "InHouse": "5", "BookedMtd": "105" }
document.getElementById("infobartemplate").setData(data);
Update: Got it to work by changing the code to:
HTMLElement.prototype.setData = function (dataObject: any): void {
alert(this.id);
}
Not sure what the difference is. I though It was the same.
That's because the lambda syntax you are using keeps the this value to the external this, by using a variable called _this, as you can see in the playground: http://past.is/wxBJm
Since the lambda is not in a class, it is bound to the "this" that is global, here the window object.
By using the function syntax, you keep the javascript behaviour, so this is bound to the object on the left hand side of the property access (dot notation).
But I think you should not add methods to a class using directly the prototype in typescript.