1

我在一个项目中工作,大部分时间我都必须导入computed style...html divs所以我尝试在下创建一个自定义prototypeObject以使我的代码变得更好、更简单、更短......这是适合我的代码...

Object.prototype.css=function(){
    return window.getComputedStyle(this);
}

什么时候var anode一个html div,我需要height那个div,我必须使用prototype下面的...

a.css().height;

现在的问题是......我怎样才能修改我function的使用prototype...

a.css.height; // css insead of css()

请不要 jQuery...

4

2 回答 2

7

如果你需要它一个属性一样工作,你必须放弃一些兼容性。仅现代浏览器支持Object.defineProperty().

这是一个例子:

function SomeType() {}
Object.defineProperty(SomeType.prototype, 'att', {
  get: function() {
    return this.att_;
  },
  set: function(value) {
    this.att_ = value;
  }
});

在您的情况下,您可以扩展HTMLElementorHTMLDivElement的原型。whereHTMLDivElement的原型继承自HTMLElement's. 所以你可以这样做:

Object.defineProperty(HTMLElement.prototype, 'css', {
  get: function(){
    return window.getComputedStyle(this);
  }
});
于 2012-11-22T14:20:41.357 回答
0

在 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()方法时存在的样式。

于 2012-11-22T14:09:54.850 回答