Dellirium Dellirium - 5 months ago 12
Javascript Question

Object's property set to native function call, wrong practice?

Javascrip can have it's object's properties refer to functions, as shown in the example. Would this be considered wrong, as in "resource heavy" or in any other way cumbersome for the system:

var someGlobalVar = {
someElement: document.getElementById("someElementsID")
};


It works, but I am wondering if it causes this call to be made every time the object is reference, or only at initialization, or when? Is it okay to write it like this?

Answer
var someGlobalVar = {
    someElement: document.getElementById("someElementsID")
};

Is equivalent to:

var someGlobalVar = {
    someElement:null
};

someGlobalVar.someElement = document.getElementById("someElementsID");

Could also:

var someGlobalVar = {

   someElement:null,

   setSomeElement:function(e) {
      this.someElement = e;
   } 

};

someGlobalVar.setSomeElement(document.getElementById("someElementsID"));
Comments