Javascript 别名接口属性
是否可以使用别名(例如,属性)的方法,就像我可以使用别名(例如)的方法一样Javascript 别名接口属性,javascript,Javascript,是否可以使用别名(例如,属性)的方法,就像我可以使用别名(例如)的方法一样 EventTarget.prototype.on = EventTarget.prototype.addEventListener 我试过: HTMLElement.prototype.w = HTMLElement.prototype.offsetWidth 但是得到: TypeError:对未调用的对象调用了“offsetWidth”getter 实现接口HtmleElement offsetWidth是一个属
EventTarget.prototype.on = EventTarget.prototype.addEventListener
我试过:
HTMLElement.prototype.w = HTMLElement.prototype.offsetWidth
但是得到:
TypeError:对未调用的对象调用了“offsetWidth”getter
实现接口HtmleElement
offsetWidth
是一个属性,当您
HTMLElement.prototype.offsetWidth
真正调用get
函数,所以当您在原型上尝试if时,您会得到错误
所以您不能指定属性,而是可以使用所有设置,然后使用此描述符,但使用您希望的名称
var descriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,“offsetWidth”);
Object.defineProperty(HTMLElement.prototype,“w”,描述符);
var p=document.getElementById('p');
log('offsetwidth=%i,w=%i',p.offsetwidth,p.w.)代码>
123
您可以获取并使用名称添加您想要的内容want@MarkC. <代码>HTMLElement.offsetWidth
为undefined@Grundy完全正确,我误读了一些东西。感谢您纠正meAwesome,效果非常好!有没有办法让类似于HTMLElement.prototype.x=HTMLElement.prototype.getBoundingClientRect().left
的东西正常工作?所以基本上是对一个方法的属性进行别名。。。?不知道这是否有意义!我得到的最接近的结果是使用Element.prototype.x=function(){返回这个.getBoundingClientRect().left}
,但也许有一些魔法可以让它在不使用括号的情况下工作?@Nightfever,如果你想Element.prototype.x
而不是Element.prototype.x()
你应该添加not function字段,但是属性
。尝试查看文档-您只需要定义getter@Nightfever,试试看更新的答案,我想现在应该更清楚了:-)