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?
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
};
This cannot work. this is window in this context.
var testObject =
{
testDiv: $("#testDiv"),
testDivProperty: this.testDiv // window.testDiv
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With