Accessing a Jquery selector as an object property, unexpected outcome
Trying to refer to the object you're defining as this
during object instantiation doesn't work like you're expecting it to.
this
in your example actually refers to the window
object. Some browsers (e.g., Chrome and IE) will attach named DOM nodes to the document
and/or window
objects, which is why this.testDiv
refers to the element with id="testDiv"
. It just so happens the property name you're trying to access has the same value as the element ID.
To demonstrate what's really going on, try this:
<div id="test"></div>
var myObj = {
prop1: $('#test'),
prop2: this.prop1
};
this.prop1
in the context of myObj
should be undefined
, but window.test
may (depending on the browser) refer to the DOM node <div id="test"></div>
.
Given your example, you could do your assignment as follows:
var myObj = { prop1: $('#test') };
myObj.prop2 = myObj.prop1;
or
var test = $('#test');
var myObj = {
prop1: test,
prop2: test
};