Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Jquery selector as an object property, unexpected outcome

Assuming I have a div that looks like:

<div id="testDiv">some stuff in here</div>

and I have a script that defines an object literal:

var testObject = 
{
    testDiv: $("#testDiv"),
    testDivProperty: this.testDiv    
};

Why is it when I access testObject.testDiv I get a reference to a jQuery object, i.e.,

[<div id=​"testDiv">​…​</div>​]

but when I access testObject.testDivProperty I get a reference to the actual element, i.e.,

<div id=​"testDiv">​…​</div>​

and hence am not able to perform jQuery operations on testObject.testDivProperty?

like image 455
x1886x Avatar asked Oct 02 '13 11:10

x1886x


2 Answers

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
};
like image 126
André Dion Avatar answered Oct 31 '22 02:10

André Dion


This cannot work. this is window in this context.

var testObject = 
{
    testDiv: $("#testDiv"),
    testDivProperty: this.testDiv // window.testDiv

}
like image 25
meagar Avatar answered Oct 31 '22 00:10

meagar