Search code examples
javascriptoopobjectobject-properties

How to use element with object property like element.myobj.prop


If I declare a object like

var obj =function(element){
return{
wide:element.clientWidth
}}

I must declare it like

var fdiv=new obj(document.etc.etc.);

and call like

fdiv.wide;

But this is quite limiting my code. I must declare new obj for each element. My question is how i can set element name dynamic in order to be able to use like nodeI_want.obj.wide or obj.nodeI_want.wide or anything like this to use my property with dynamically given node. note:clientWidth prop. is just an example to clarify it will be replaced in my code with my own properties.


Solution

  • You seem to be wanting to extend HTMLElement. The proper way to do it is by adding your method to the prototype of HTMLElement.

    For example (I didn't use your original function code because it's quite vague in what it tried to achieve):

    HTMLElement.prototype.getMyWidth = function() {
        return this.clientWidth;
    };
    

    See HTMLElement