views:

24

answers:

2

Ok I'm not sure the title of this post is the correct way to refer to what I mean and I'm pretty sure I already know the answer to this question but I just wanted some clarification.

If I have an oject like this

var myObj = {
  settings : {
    domObj = document.getElementById('elem1');
  },
  myFunc1 : function () {
    return this.domObj;
  },
  myFunc2 : function () {
    return this.domObj;
  }
}

myObj.myFunc1();
myObj.myFunc2();

Is the domObj cached the first time it is accessed or is the dom traversed in both functions? I am attempting to access the Dom only once but not sure if this is a possible solution.

+1  A: 

Assuming you really meant this:

var myObj = {
  settings : function() {
    domObj = document.getElementById('elem1');
  },
  myFunc1 : function() {
    return this.domObj;
  },
  myFunc2 : function() {
    return this.domObj;
  }
};

the answer is that "domObj" is a global variable because you forgot the var keyword. Now, you may have meant this:

var myObj = {
  domObj: null,
  settings : function() {
    this.domObj = document.getElementById('elem1');
  },
  myFunc1 : function() {
    return this.domObj;
  },
  myFunc2 : function() {
    return this.domObj;
  }
};

in which case "domObj" is just a property of "myObj". It'd get set if you call

myObj.settings();
Pointy
+1  A: 

Assuming your doing "this.domObj =" and the other corrections you've noted; yes; the DOM element is cached in this.domObj. The only time the DOM is actually traversed is when you're calling DOM traversal methods. Assigning a DOM element to a variable/object property works exactly the same as any other assignment.

Angiosperm