Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing interface property

Tags:

javascript

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.

like image 753
Nightfever Avatar asked Nov 03 '15 19:11

Nightfever


1 Answers

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>
like image 105
Grundy Avatar answered Nov 06 '22 04:11

Grundy