我在一个项目中工作,大部分时间我必须导入computed style of html divs.因此,我尝试在Object下创建一个自定义的Object,使我的代码变得更好、更简单和更短……这是对我有用的密码..。
Object.prototype.css=function(){
return window.getComputedStyle(this);
}当var a是node of a html div而我需要height of height div时,我必须像下面这样使用prototype .
a.css().height;问题是..。我如何修改我的function来使用prototype,就像.
a.css.height; // css insead of css()不jQuery请.
发布于 2012-11-22 14:20:41
如果您需要它作为一个属性,您必须放弃一些兼容性。只有现代浏览器才支持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);
}
});发布于 2012-11-22 14:09:54
在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()方法时存在的样式。
https://stackoverflow.com/questions/13514277
复制相似问题