Naz
Naz

Reputation: 2775

js create advance prototype

I am working in a project where most of the time I have to import the computed style of html divs... so I have tried to create a custom prototype under Object to make my code little nice, simple and shorter... here is the code that works for me...

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

when var a is the node of an html div and I need the height of that div, I have to use the prototype like below...

a.css().height;

Now the question is... how can I modify my function to use the prototype like...

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

no jQuery please...

Upvotes: 1

Views: 105

Answers (2)

xiaoyi
xiaoyi

Reputation: 6741

If you need it to act like an property, you have to give up some compatibility. For only modern browsers support Object.defineProperty().

Here is an example:

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

And in your case, you can extend HTMLElement or HTMLDivElement's prototypes. Where HTMLDivElement's prototype is inherited from HTMLElement's. So you can do it like:

Object.defineProperty(HTMLElement.prototype, 'css', {
  get: function(){
    return window.getComputedStyle(this);
  }
});

Upvotes: 7

teddybeard
teddybeard

Reputation: 2014

In Javascript, functions are first class objects. Basically, a function definition is just like any other variable. You can assign all of the following to a property:

a.css = "some value";
a.css = 22;
a.css = function() { return 1; };

now if you try to print them:

a.css //"some value"
a.css //22
a.css //function (){return 1;}

In order to invoke the function, you need to call a.css(). One way to get the desired behavior would be to execute the function and bind the output to another property.

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

a.makeCSSProperty();
a.css.height;

However, this property will be static and only reflect the style as it existed when you ran the makeCSSProperty() method.

Upvotes: 0

Related Questions