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, ie,

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

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

<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 (eg, 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

}

After some playing around I found the answer. At the time that you create the 2nd property, this refers to window , where you have a div with the id of testDiv .

So you're actually doing this...

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

I personally wasn't aware that you could do this, but window.testDiv returns the DOM element with the ID testDiv .

链接地址: http://www.djcxy.com/p/16316.html

上一篇: Android模拟器永远不会禁用相机

下一篇: 访问一个Jquery选择器作为对象属性,意想不到的结果