Get value of named object

Discussion in 'Javascript' started by Swifty, Oct 22, 2011.

  1. Swifty

    Swifty Guest

    Swifty, Oct 22, 2011
    #1
    1. Advertising

  2. Swifty

    Evertjan. Guest

    Swifty wrote on 22 okt 2011 in comp.lang.javascript:

    > If I have the name of an object in a variable, how would I go about
    > getting the value of that object?


    myObject.name perhaps would return the name of an object.

    >
    > Example:
    > varname = 'navigator.appName';
    >
    > How would I get the value of navigator.appName ?
    >
    > See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.
    >
    > The idea is to replace the multiple "document.write" lines with the
    > simpler "show()" calls.


    document.write( "<TR><TH>" + varname + "<TD>" + eval(varname) );

    =================

    Using eval() indeed is a variable blessing:

    <H1>JavaScript Varibles</H1>

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
     
    Evertjan., Oct 22, 2011
    #2
    1. Advertising

  3. Swifty wrote:

    > If I have the name of an object in a variable,


    That is _not_ the name of an object (objects have _identity_, not name). It
    is a possible reference path of a property (a property accessor) which value
    refers to that object.

    > how would I go about getting the value of that object?
    >
    > Example:
    > varname = 'navigator.appName';
    >
    > How would I get the value of navigator.appName ?


    eval(varname). But you really don't want to do that.

    > See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.
    >
    > The idea is to replace the multiple "document.write" lines with the
    > simpler "show()" calls.


    (Your current show() would still cause document.write() to be called
    consecutively, which is a bad idea.)

    Consider this:

    var properties = [
    ["navigator", "appCodeName"],
    ["screen", "availHeight", "availWidth"],
    ["window", "closed", "history", "innerHeight", "innerWidth",
    ["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
    ];

    Then iterate recursively over this data structure, starting with

    _global[properties[0]]

    where `_global' is a reference to the ECMAScript global object (`this' in
    the global execution context) and `i' is the iterator variable. Complete
    and improve this:

    var out = [];

    for (var i = 0, len = properties.length; i < len; ++i)
    {
    var base = properties[0];
    for (var properties2 = properties, len2 = properties2.length, j = 1;
    j < len2; ++j)
    {
    var property = base[j];
    out.push(
    "…" + base + "." + property + "…" + _global[base][property] + "…");
    }
    }

    document.write("…" + out.join("…") + "…");

    You may use Object instances as well if you do not care about order or
    iterate over property values in an order that you define. In any case,
    you have to take care of inherited and special properties, then.


    PointedEars
    --
    Use any version of Microsoft Frontpage to create your site.
    (This won't prevent people from viewing your source, but no one
    will want to steal it.)
    -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
     
    Thomas 'PointedEars' Lahn, Oct 22, 2011
    #3
  4. Swifty wrote:

    > If I have the name of an object in a variable,


    That is _not_ the name of an object (objects have _identity_, not name). It
    is a possible reference path of a property (a property accessor) which value
    refers to that object.

    > how would I go about getting the value of that object?
    >
    > Example:
    > varname = 'navigator.appName';
    >
    > How would I get the value of navigator.appName ?


    eval(varname). But you really don't want to do that.

    > See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.
    >
    > The idea is to replace the multiple "document.write" lines with the
    > simpler "show()" calls.


    (Your current show() would still cause document.write() to be called
    consecutively, which is a bad idea.)

    Consider this:

    var properties = [
    ["navigator", "appCodeName"],
    ["screen", "availHeight", "availWidth"],
    ["window", "closed", "history", "innerHeight", "innerWidth",
    ["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
    ];

    Then iterate recursively over this data structure, starting with

    _global[properties[0]]

    where `_global' is a reference to the ECMAScript global object (`this' in
    the global execution context) and `i' is the iterator variable. Complete
    and improve this:

    var out = [];

    for (var i = 0, len = properties.length; i < len; ++i)
    {
    var properties2 = properties;
    var base = properties2[0];
    for (var j = 1, len2 = properties2.length; j < len2; ++j)
    {
    var property = base[j];
    out.push(
    "…" + base + "." + property + "…" + _global[base][property] + "…");
    }
    }

    document.write("…" + out.join("…") + "…");

    You may use Object instances as well if you do not care about order or
    if you iterate over property values in an order that you define. In any
    case, you have to take care of inherited and special properties, then.

    Since you are dealing with host objects here, you have to be extra careful
    with "unknown"-type properties and to catch any exceptions a property access
    can throw.


    PointedEars
    --
    Use any version of Microsoft Frontpage to create your site.
    (This won't prevent people from viewing your source, but no one
    will want to steal it.)
    -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
     
    Thomas 'PointedEars' Lahn, Oct 22, 2011
    #4
  5. Swifty wrote:

    > If I have the name of an object in a variable,


    That is _not_ the name of an object (objects have _identity_, not name). It
    is a possible reference path of a property (a property accessor) which value
    refers to that object.

    > how would I go about getting the value of that object?
    >
    > Example:
    > varname = 'navigator.appName';
    >
    > How would I get the value of navigator.appName ?


    eval(varname). But you really don't want to do that.

    > See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.
    >
    > The idea is to replace the multiple "document.write" lines with the
    > simpler "show()" calls.


    (Your current show() would still cause document.write() to be called
    consecutively, which is a bad idea.)

    Consider this:

    var properties = [
    ["navigator", "appCodeName"],
    ["screen", "availHeight", "availWidth"],
    ["window", "closed", "history", "innerHeight", "innerWidth",
    ["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
    ];

    Then iterate recursively over this data structure, starting with

    _global[properties[0]]

    where `_global' is a reference to the ECMAScript global object (`this' in
    the global execution context) and `i' is the iterator variable. Complete
    and improve this:

    var out = [];

    for (var i = 0, len = properties.length; i < len; ++i)
    {
    var properties2 = properties;
    var base = properties2[0];
    for (var j = 1, len2 = properties2.length; j < len2; ++j)
    {
    var property = properties2[j];
    out.push(
    "…" + base + "." + property + "…" + _global[base][property] + "…");
    }
    }

    document.write("…" + out.join("…") + "…");

    You may use Object instances as well if you do not care about order or
    if you iterate over property values in an order that you define. In any
    case, you have to take care of inherited and special properties, then.

    Since you are dealing with host objects here, you have to be extra careful
    with "unknown"-type properties and to catch any exceptions a property access
    can throw.


    PointedEars
    --
    Use any version of Microsoft Frontpage to create your site.
    (This won't prevent people from viewing your source, but no one
    will want to steal it.)
    -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
     
    Thomas 'PointedEars' Lahn, Oct 22, 2011
    #5
  6. Swifty

    Swifty Guest

    On 22 Oct 2011 11:20:48 GMT, "Evertjan."
    <> wrote:

    >Using eval() indeed is a variable blessing:
    >
    ><H1>JavaScript Varibles</H1>


    Thanks for that, and eval()

    I realise that eval() is disliked, as is the "Interpret" instruction
    which does something similar in my usual language.

    --
    Steve Swift
    http://www.swiftys.org.uk/swifty.html
    http://www.ringers.org.uk
     
    Swifty, Oct 22, 2011
    #6
  7. Swifty

    Swifty Guest

    On Sat, 22 Oct 2011 14:35:56 +0200, Thomas 'PointedEars' Lahn
    <> wrote:

    >(Your current show() would still cause document.write() to be called
    >consecutively, which is a bad idea.)


    And there I was, congratulating myself on having very nearly written
    an entire page in JavaScript. One step at a time.

    The page is half learning exercise, half reference for properties that
    interest me, and which I may eventually use somewhere.

    --
    Steve Swift
    http://www.swiftys.org.uk/swifty.html
    http://www.ringers.org.uk
     
    Swifty, Oct 22, 2011
    #7
  8. Swifty wrote:

    > […] "Evertjan." wrote:
    >> Using eval() indeed is a variable blessing:
    >>
    >> <H1>JavaScript Varibles</H1>

    >
    > Thanks for that, and eval()
    >
    > I realise that eval() is disliked, as is the "Interpret" instruction
    > which does something similar in my usual language.


    "Disliked" does not quite describe it.


    PointedEars
    --
    Prototype.js was written by people who don't know javascript for people
    who don't know javascript. People who don't know javascript are not
    the best source of advice on designing systems that use javascript.
    -- Richard Cornford, cljs, <f806at$ail$1$>
     
    Thomas 'PointedEars' Lahn, Oct 22, 2011
    #8
  9. Swifty wrote:

    > Thomas 'PointedEars' Lahn wrote:
    >> (Your current show() would still cause document.write() to be called
    >> consecutively, which is a bad idea.)

    >
    > And there I was, congratulating myself on having very nearly written
    > an entire page in JavaScript. One step at a time.
    >
    > The page is half learning exercise, half reference for properties that
    > interest me, and which I may eventually use somewhere.


    If it is supposed to be a learning exercise, then you have slept right
    through it. In essence:

    1. Avoid using eval(). Use property access syntax instead.

    2. Do not call document.write() consecutively. Pass it a string value
    (or a value convertible to a string) that you build before.


    PointedEars
    --
    Anyone who slaps a 'this page is best viewed with Browser X' label on
    a Web page appears to be yearning for the bad old days, before the Web,
    when you had very little chance of reading a document written on another
    computer, another word processor, or another network. -- Tim Berners-Lee
     
    Thomas 'PointedEars' Lahn, Oct 22, 2011
    #9
  10. Swifty

    Scott Sauyet Guest

    Swifty wrote:
    > If I have the name of an object in a variable, how would I go about
    > getting the value of that object?
    >
    > Example:
    > varname = 'navigator.appName';
    >
    > How would I get the value of navigator.appName ?
    >
    > Seehttp://swiftys.org.uk/jsvars.htmlfor my first, faltering attempt.


    An approach somewhat different from Thomas', and perhaps not as safe,
    is the following:

    var interpret = (function() {
    var global = this;
    return function(str) {
    var idx, obj, context = arguments[1] || global;
    if (!str || typeof str != "string") return null;
    idx = str.indexOf(".");
    if (idx > -1) {
    obj = context[str.substring(0, idx)];
    return interpret(str.substring(idx + 1), obj);
    } else {
    return context[str];
    }
    }
    }());

    console.log(interpret("navigator.appName"));
    // Or document.write, or alert, or DOM manipulation

    This will not work if you have a property name that includes a ".",
    and it might have problems Thomas suggested with Host objects, but for
    many use cases it will work fine.

    -- Scott
     
    Scott Sauyet, Oct 22, 2011
    #10
  11. Swifty <> writes:

    > If I have the name of an object in a variable, how would I go about
    > getting the value of that object?
    >
    > Example:
    > varname = 'navigator.appName';
    >


    So this is the reference:
    globalObject["navigator"]["appName"]

    So:
    <script>
    var global = this;
    function EvalReference(name) {
    var parts = name.split(/\./g);
    var current = global;
    for (var i = 0; i < parts.length; i++) {
    current = current[parts];
    }
    return current;
    }
    </script>

    Then you can do:
    EvalReference("navigator.appName"]
    and get the expected result.

    Yes, you can use eval instead. You must be certain to use global eval,
    by calling it as an indirect call (not called "eval"). E.g.,
    var indirectEval = eval;
    var value = indirectEval("navigator.appName");
    I still think it's a bad idea.

    /L
    --
    Lasse Reichstein Holst Nielsen
    'Javascript frameworks is a disruptive technology'
     
    Lasse Reichstein Nielsen, Oct 23, 2011
    #11
  12. In comp.lang.javascript message <a185a7pdddj3ui58j7a8rrtuivpe4gu92l@4ax.
    com>, Sat, 22 Oct 2011 11:56:39, Swifty <>
    posted:

    >If I have the name of an object in a variable, how would I go about
    >getting the value of that object?
    >
    >Example:
    >varname = 'navigator.appName';
    >
    >How would I get the value of navigator.appName ?



    var Arr = varname.split(".") // gives ["navigator","appName"]

    IIRC, there are only a few possibilities for Arr[0], so
    var Obj = {"navigator": navigator; "document": document /*, ,,, */}
    is feasible.

    var Obj = {"navigator": navigator, "document": document,
    "Math": Math /*, ,,, */}

    var varname = 'navigator.appName';
    var Arr = varname.split(".")
    Result = Obj[Arr[0]][Arr[1]]

    gives "Netscape", and for "Math.PI" gives about 22/7, and for
    "document.writeln" gives "function writeln() { [native code]}".
    Now make that a function.

    To allow for inputs with other than one dot, start with Result=Obj, then
    iterate through Arr (in the right direction) doing each index in turn.
    Untested, therefore code not written here.

    You might like <http://www.merlyn.demon.co.uk/js-props.htm>.

    >The idea is to replace the multiple "document.write" lines with the
    >simpler "show()" calls.


    Consider
    var Arr = []
    Arr.push("6")
    Arr.push(" fred")
    document.write(A,join(""))
    which is less typing per line of code.

    --
    (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
    Website <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
    PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
    Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
     
    Dr J R Stockton, Oct 23, 2011
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Asaf
    Replies:
    0
    Views:
    467
  2. Scott M.
    Replies:
    0
    Views:
    367
    Scott M.
    Feb 5, 2004
  3. bruce barker
    Replies:
    2
    Views:
    659
    =?Utf-8?B?am9obl9jYQ==?=
    Feb 6, 2004
  4. Tommy
    Replies:
    0
    Views:
    395
    Tommy
    Feb 5, 2004
  5. Tuxedo
    Replies:
    2
    Views:
    573
    Tuxedo
    Feb 14, 2012
Loading...

Share This Page