
[英]How to create a JS object with the default prototype from an object without a prototype?
[英]js create advance prototype
我在一个项目中工作,在大多数情况下,我必须导入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()
请不要jQuery ...
如果你需要它像一个财产法,你必须放弃一些兼容性。 仅现代浏览器支持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()
方法时存在的样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.