Is it possible to alias e.g. the HTMLElement.offsetWidth property, the same way I can alias methods like
EventTarget.prototype.on = EventTarget.prototype.addEventListener
I tried:
HTMLElement.prototype.w = HTMLElement.prototype.offsetWidth
but got:
TypeError: 'offsetWidth' getter called on an object that does not implement interface HTMLElement.
offsetWidth
is a property, and when you do
HTMLElement.prototype.offsetWidth
really calling get
function, so when you try if on prototype - you get error.
So you can't assign property, instead you can get descriptor for this property with all settings, and then define property with this descriptor, but with name that you wish.
var descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetWidth");
Object.defineProperty(HTMLElement.prototype, "w", descriptor);
var p = document.getElementById('p');
console.log('offsetwidth=%i, w=%i',p.offsetWidth,p.w);
<p id='p'>123</p>
and then you can call new w
property on existing HTMLElement.
UPDATE for your comment.
If you want add function to object and call it without ()
you should define property with getter.
For more info about properties with sample see in doc: MDN : Object.defineProperty()
Object.defineProperty(HTMLElement.prototype, "x", {
get: function() { return this.getBoundingClientRect().left }
});
var p = document.getElementById('p');
console.log('left=%i, x=%i',p.getBoundingClientRect().left,p.x);
<p id='p'>123</p>
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