Naz*_*azi 1 javascript prototype function
我在一个项目中,大部分时间我不得不进口工作computed style的html divs...所以我试图创建一个自定义prototype下,Object使我的一点不错,简单和更短......这里是为我工作的代码...
Object.prototype.css=function(){
return window.getComputedStyle(this);
}
Run Code Online (Sandbox Code Playgroud)
当var a是node的html div,我需要height的是div,我必须使用prototype像下面...
a.css().height;
Run Code Online (Sandbox Code Playgroud)
现在的问题是......我怎么能修改我function使用的prototype...
a.css.height; // css insead of css()
Run Code Online (Sandbox Code Playgroud)
没有jQuery请...
如果你需要它像一个属性,你必须放弃一些兼容性.仅适用于现代浏览器支持Object.defineProperty().
这是一个例子:
function SomeType() {}
Object.defineProperty(SomeType.prototype, 'att', {
get: function() {
return this.att_;
},
set: function(value) {
this.att_ = value;
}
});
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以扩展HTMLElement或HTMLDivElement原型.其中HTMLDivElement的原型是继承自HTMLElementS'.所以你可以这样做:
Object.defineProperty(HTMLElement.prototype, 'css', {
get: function(){
return window.getComputedStyle(this);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |