0

for my website with jquery and jquery.ui loaded i tried the following experiment.

If in the chrome console i type...

jQuery.ui
>Object {version: "1.9.1", keyCode: Object, ie: false, ie6: false, plugin: Object…}

but if i ask for its type i get..

typeof this["jQuery.ui"]
>"undefined"

Could someone explain why this is? how would/should i tell if jQuery.ui exists?.... if the "jQuery.ui" name was contained within a string variable, how would i use that variable to check existance..e.g.

var myvar = "jQuery.ui";
typeof this[myvar];  
joe Lovick
  • 59
  • 6
  • 4
    You'd need to use `this["jQuery"]["ui"]` to get a property of a property. Just do `typeof jQuery.ui`. Why would you have that "name" as a string value? – Bergi Oct 02 '14 at 22:05
  • 1
    See my answer here http://stackoverflow.com/questions/18891939/javascript-retrieve-object-property-path/18892019#18892019 – elclanrs Oct 02 '14 at 22:14
  • So from this i gather, that using string quotes i can call a variable something involving a period, eg. Jquery.ui. but if i actually want to refer to a property of a property i need to split it as Bergi says above. As to why, i am writing a generic javascript loading routine and thought it would be fun to do it this way. – joe Lovick Oct 02 '14 at 22:48

2 Answers2

2

When you type jQuery.ui you are accessing the global variable jQuery and then asking that object for a property named ui.

this["jQuery.ui"] asks the global object for a property named "jQuery.ui". Which is a totally different thing.

how would/should i tell if jQuery.ui exists?

The easiest would be:

if (jQuery && jQuery.ui) {
  // jQuery.ui exists
}

if the "jQuery.ui" name was contained within a string variable, how would i use that variable to check existance

Don't do this. Do not store the names of variables as strings. It's a bad idea. Especially if you are trying to inspect global variables.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
1

if the "jQuery.ui" name was contained within a string variable, how would i use that variable to check existance

If you really want to accomplish this, try the following code:

function existsOn(prop, obj){
    var parts = prop.split('.');
    for(var i=0; i < parts.length; i++){
        obj = obj[parts[i]];
        if(!obj){
            return false;
        }
    }
    if(obj){
        return true;
    }
    return false;
}
var str = "jQuery.ui";
alert("Exists: " + existsOn(str, window));
Trevor
  • 13,085
  • 13
  • 76
  • 99