我正在一个项目中工作,大多数时候我必须导入html divs
的computed style
......所以我尝试在Object
下创建自定义prototype
,以使我的代码变得漂亮、简单和简短......这是对我有用的代码...
Object.prototype.css=function(){
return window.getComputedStyle(this);
}
当var a
是html div
的node
并且我需要该div
的height
时,我必须使用如下所示的prototype
...
a.css().height;
现在的问题是...如何修改我的function
以使用类似prototype
...
a.css.height; // css insead of css()
请不要查询...
如果你需要它像一个属性一样,你必须放弃一些兼容性。对于仅现代浏览器支持Object.defineProperty()
.
下面是一个示例:
function SomeType() {}
Object.defineProperty(SomeType.prototype, 'att', {
get: function() {
return this.att_;
},
set: function(value) {
this.att_ = value;
}
});
在您的情况下,您可以扩展HTMLElement
或HTMLDivElement
的原型。HTMLDivElement
的原型继承自HTMLElement
的原型。所以你可以这样做:
Object.defineProperty(HTMLElement.prototype, 'css', {
get: function(){
return window.getComputedStyle(this);
}
});
在Javascript中,函数是第一类对象。基本上,函数定义就像任何其他变量一样。您可以将以下所有内容分配给属性:
a.css = "some value";
a.css = 22;
a.css = function() { return 1; };
现在,如果您尝试打印它们:
a.css //"some value"
a.css //22
a.css //function (){return 1;}
为了调用该函数,您需要调用a.css()
。获取所需行为的一种方法是执行函数并将输出绑定到另一个属性。
Object.prototype.makeCSSProperty=function(){
this.css = window.getComputedStyle(this);
}
a.makeCSSProperty();
a.css.height;
但是,此属性将是静态的,并且仅反映运行 makeCSSProperty()
方法时存在的样式。