simple variables as properties?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • optimistx

    simple variables as properties?

    A variable in global scope

    var a1 = 'contents of global variable a1';

    can be references (with some limitations) as

    window['a1']; // or
    window.a1; // or even
    window['a'+'1'];

    Thus the variable name a1 can be constructed on the fly, dynamically.
    Whether
    that is useful ... at least it is fun. One could play with selfmodifying
    code.

    If the variable is local inside a function

    var f = function () {
    var a1 = 'contents of local variable a1 inside f';
    this.b1 = 'contents of this.b1 inside f';

    // how to refer to variable a1 as a property of something? x['a1'] ?
    what is x?
    return a1;
    }

    I am a bit (!) confused: functions are objects, but
    var a1 inside f is not a property or is it?
    Variable this.b1 is actually global, at least the
    variable b1 below was overwritten in a test.

    var b1 = 'global variable b1 contents';

    So, the question is:

    // how to refer to variable a1 as a property of something, if
    var a1 is inside the function f? x['a1'] ? what is x? Or is it
    impossible?





  • Henry

    #2
    Re: simple variables as properties?

    On Sep 2, 4:18 pm, optimistx wrote:
    A variable in global scope
    >
    var a1 = 'contents of global variable a1';
    >
    can be references (with some limitations) as
    >
    window['a1']; // or
    window.a1; // or even
    window['a'+'1'];
    >
    Thus the variable name a1 can be constructed on the
    fly, dynamically.
    Whether that is useful ... at least it is fun.
    It is useful.
    One could play with selfmodifying
    code.
    >
    If the variable is local inside a function
    >
    var f = function () {
    var a1 = 'contents of local variable a1 inside f';
    this.b1 = 'contents of this.b1 inside f';
    >
    // how to refer to variable a1 as a property of
    something? x['a1'] ?
    You don't.
    what is x?
    The "Variable" object belonging to the execution context.
    return a1;
    >
    }
    >
    I am a bit (!) confused: functions are objects, but
    var a1 inside f is not a property or is it?
    It is, but it is a property of the execution context's Variable
    object, which is not directly accessible with javascript.
    Variable this.b1 is actually global,
    Depending on how you call your function (as how a function is called
    determines the value of - this - ).
    at least the
    variable b1 below was overwritten in a test.
    >
    var b1 = 'global variable b1 contents';
    >
    So, the question is:
    >
    // how to refer to variable a1 as a property of something,
    You cannot, and don't need to.
    if var a1 is inside the function f?
    There is no sense in which that is true, except lexically.
    x['a1'] ? what is x? Or is it
    impossible?
    Variable objects are inaccessible. If you need to reference properties
    of an object that is local to an execution context, create one, assign
    values to its properties and reference them as properties of that
    object.

    Comment

    • optimistx

      #3
      Re: simple variables as properties?

      Henry wrote:
      ....
      >
      Variable objects are inaccessible. If you need to reference properties
      of an object that is local to an execution context, create one, assign
      values to its properties and reference them as properties of that
      object.
      /*Thanks for your explanation. To be sure that I understood correctly I try
      to repeat with my own words and an example.*/

      var a1 ='outside a1';
      var b1 ='outside b1';

      var f = function () {
      var a1 ='inside a1';
      this.b1 = 'inside b1';
      alert('a1 = ' + a1 + '\nb1 = ' + this.b1);
      }

      f();
      alert(('a1 = ' + a1 + '\nb1 = ' + b1);


      /*
      Having learnt that

      1) 'functions are objects'
      2) 'this refers to the current object'
      3) 'scope is something obscure, but there is global scope and not-so-global
      scopes and
      scope depends on how you come to it'
      4) microsoft, jquery, eval belong to the evil empire and you shoul tell that
      oftern, amen

      I would have guessed that

      1) variable this.b1 inside is different from var b1 outside (* wrong!*)
      2) var a1 inside f would be an accessible property of something (*wrong!*)
      3) having called f by f() the scope of execution would be the object f, all
      its local variables would belong to the scope, 'local scope' (*wrong?!*)

      If we pick an average newbie with some hours of javascript learning, how
      would she/he know and learn these effectively and in an easy-to-remember
      way? Pictures? Lengthy text explanations do not help me. I understand
      something, if I can explain it to a 7-10 year old child so that the child
      explains it to me correctly with his/her own words and pictures. A
      collection 'you might think javascript works like this (example with
      pictures ), but that is wrong!, it works like this (example with pictures)
      might be useful for learning...

      */


      Comment

      • Gregor Kofler

        #4
        Re: simple variables as properties?

        optimistx meinte:

        [snip]
        3) 'scope is something obscure, but there is global scope and not-so-global
        scopes and
        scope depends on how you come to it'
        Nope. JS has function scope. That's all.
        1) variable this.b1 inside is different from var b1 outside (* wrong!*)
        No. Because in your case "this" refers to the global object.
        2) var a1 inside f would be an accessible property of something (*wrong!*)
        Why? It's only accessible within the matching scope. That's the way to
        implement private "properties " in JS.
        3) having called f by f() the scope of execution would be the object f, all
        its local variables would belong to the scope, 'local scope' (*wrong?!*)
        I suppose the answer is "yes".
        Lengthy text explanations do not help me. I understand
        something, if I can explain it to a 7-10 year old child so that the child
        explains it to me correctly with his/her own words and pictures.
        I doubt it will go without reading. And I'm not sure whether toddlers
        are interested in client side scripting...

        Gregor


        --
        http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
        http://web.gregorkofler.com ::: meine JS-Spielwiese
        http://www.image2d.com ::: Bildagentur für den alpinen Raum

        Comment

        • Jorge

          #5
          Re: simple variables as properties?

          On Sep 3, 8:50 am, "optimistx" <optimistxPoi.. .@poistahotmail .com>
          wrote:
          >
          1) variable this.b1 inside is different from var b1 outside (* wrong!*)
          this.b1 is the property b1 of the object that 'this' points to.
          ** in this case **, 'this' points to the global object (this.b1 ===
          window.b1), and the outside var b1 happens to be === window.b1 (it's a
          global).
          2) var a1 inside f would be an accessible property of something (*wrong!*)
          It's an accesible property of an inaccesible object, if you want : you
          can access it only within f() by its name (a1).

          --
          Jorge.

          Comment

          • Henry

            #6
            Re: simple variables as properties?

            On Sep 3, 7:50 am, optimistx wrote:
            Henry wrote:
            ...
            >Variable objects are inaccessible. If you need to reference
            >properties of an object that is local to an execution context,
            >create one, assign values to its properties and reference
            >them as properties of that object.
            >
            /*Thanks for your explanation. To be sure that I understood
            correctly I try to repeat with my own words and an example.*/
            >
            var a1 ='outside a1';
            var b1 ='outside b1';
            >
            var f = function () {
            var a1 ='inside a1';
            this.b1 = 'inside b1';
            alert('a1 = ' + a1 + '\nb1 = ' + this.b1);
            >
            }
            >
            f();
            alert(('a1 = ' + a1 + '\nb1 = ' + b1);
            >
            /*
            Having learnt that
            >
            1) 'functions are objects'
            Broadly irrelevant in this context.
            2) 'this refers to the current object'
            There is nothing in javascript that provides meaning for the phrase
            "current object", beyond the trivial and circular; the "current object
            is the object referred to by the - this - keyword, and the - this -
            keyword refers to the "current object" (in which there is clearly no
            point in introducing "current object" as it adds nothing useful).
            3) 'scope is something obscure,
            No it is not. Scopes consist of chains (or lists) of objects and are
            100% predictable/consistent. Each execution context has a scope and
            each function object has an internal [[Scope]] property that is used
            to determine the scope for the execution context that come into
            existence when it is executed. (A function execution context's scope
            is the scope chain consisting of the chain referred to by the
            function's [[Scope]] property with a Variable/Activation object added
            to the end/top of the chain/list).

            Note: much uniformed writing on javascript erroneously employs the
            term 'scope' when talking about the - this - keyword. This is an
            indication of an author not understanding what they are talking about
            (with the obvious implications for the veracity of their words).
            but there is global scope
            There is a global execution context, which has a scope, which is a
            scope chain containing only one object, and that one object is the
            global object. The global object is also at the end of every other
            scope chain. The term "global scope" is usually employed as shorthand
            for the properties of the global object (which, because the global
            object is at the end of all scope chains, are (unless masked more
            locally) globally accessible using Identifiers).
            and not-so-global
            scopes and
            scope depends on how you come to it'
            No, scopes are lexical; they are determined by the structure of the
            source code, except where - with - is used to explicitly add arbitrary
            objects to the scope chain of an execution context.
            4) microsoft, jquery, eval belong to the evil empire and you
            shoul tell that oftern, amen
            The last things that will help with programming are mystical beliefs.
            I would have guessed that
            >
            1) variable this.b1 inside is different from var b1 outside (* wrong!*)
            Variables declared in the global execution context become properties
            of the global object because the global execution context uses the
            global object as its Variable object. In a function called as above
            the - this - keyword will refer to the global object, and so this.b1
            will refer to the 'b1' property of the global object, which is the
            property created for the variable - b1 - and assigned the value
            'outside b1'.
            2) var a1 inside f would be an accessible property of something
            (*wrong!*)
            3) having called f by f() the scope of execution would be the
            object f,
            But "object f" is a function object, and there is not really such a
            thing as a "scope of execution", except possibly the scope belonging
            to the execution context of a call to f.
            all its local variables would belong to the scope,
            'local scope' (*wrong?!*)
            All the local variable do belong to the local scope (in as far as that
            is meaningful at all); they are named properties of the Variable
            object, and the Variable object is the object at the top of the
            execution context's scope chain.
            If we pick an average newbie
            That would not be a useful thing to do because there are two very
            divergent entry points to learning javascript; the programmer familiar
            with other languages and designer/HTML author exposed to programming
            for the first time. the average of those two would be fare from
            representative of either.
            with some hours of javascript learning,
            Hours?
            how would she/he know and learn these effectively and in an
            easy-to-remember way?
            Remembering it best encouraged by understanding.
            Pictures?
            What would be the shape and color of an execution context, a function,
            a variable?
            Lengthy text explanations do not help me.
            Given sufficient (and assuming authors who know what they are talking
            about and use correct and consistent terminology) then they probably
            will help.
            I understand something, if I can explain it to a 7-10 year
            old child so that the child explains it to me correctly with
            his/her own words and pictures.
            If you are only capable of understanding things that can be understood
            by a 7-10 year old then maybe this subject is beyond you.
            A collection 'you might think javascript works like this
            (example with pictures ), but that is wrong!, it works like
            this (example with pictures) might be useful for learning...
            So when you have learnt you can create those, if you still think they
            would be a good idea.

            Comment

            • optimistx

              #7
              Re: simple variables as properties?

              Gregor Kofler wrote:
              optimistx meinte:
              >>...
              >>I understand
              >something, if I can explain it to a 7-10 year old child so that the
              >child explains it to me correctly with his/her own words and
              >pictures.
              >
              I doubt it will go without reading. And I'm not sure whether toddlers
              are interested in client side scripting...
              >
              Gregor
              That might be a joke, but after checking 'define toddler' with google,
              I got the impression of toddlers being 1-3 year old children. We
              probably both agree, that most of them are not interested in learning
              javascript.

              My children were interested in learning pascal in the age of 7-10 years,
              and wrote small games with that language.


              Comment

              • optimistx

                #8
                Re: simple variables as properties?

                Henry wrote:
                ....
                On Sep 3, 7:50 am, optimistx wrote:
                >I understand something, if I can explain it to a 7-10 year
                >old child so that the child explains it to me correctly with
                >his/her own words and pictures.
                >
                If you are only capable of understanding things that can be understood
                by a 7-10 year old then maybe this subject is beyond you.
                ....
                Thanks for your answer. I'll keep that in mind and study carefully.

                Obviously I have to learn the specific meanings of
                the words 'scope', 'function', 'object', 'this', 'context', 'current',
                'method',
                'property', 'activation object',' 'variable object' as they are defined in
                (list of all the authorized sources of comp.lang.javas cript here).
                I see now that my first understanding of the word 'scope' differs from the
                strict meaning of the word 'scope' as defined in .../ECMA-262.pdf :
                'this' and 'scope' are still quite fuzzy for me. I greatly admire anyone,
                who in some seconds can reliably see the correct interpretation of those,
                when
                looking at any new code sequence.



                Comment

                • Henry

                  #9
                  Re: simple variables as properties?

                  On Sep 4, 10:41 am, optimistx wrote:
                  Henry wrote:
                  >On Sep 3, 7:50 am, optimistx wrote:
                  >>I understand something, if I can explain it to a 7-10 year
                  >>old child so that the child explains it to me correctly with
                  >>his/her own words and pictures.
                  >
                  >If you are only capable of understanding things that can be
                  >understood by a 7-10 year old then maybe this subject is
                  >beyond you.
                  >
                  ...
                  Thanks for your answer. I'll keep that in mind and study
                  carefully.
                  >
                  Obviously I have to learn the specific meanings of
                  the words 'scope', 'function', 'object', 'this', 'context',
                  'current', 'method', 'property', 'activation object',
                  ' 'variable object'
                  Current and context have no special/specific meaning in terms of
                  javascript. There are entities called "execution contexts".

                  Scope and method are general concepts that are not strictly defined.
                  Scope is effectively defined by the rules relating to the creation and
                  assignment of scope chains and the resolution of identifiers against
                  scope chains. Methods are unhelpfully described as function value
                  properties of objects, but the concept of 'method' only fits when
                  those functions are called in particular ways (as it is how they are
                  called that determines the - this - value).
                  as they are defined in
                  (list of all the authorized sources of comp.lang.javas cript here).
                  ECMA 262 (usually 3rd Ed (for now (3.1 is planed for next year))). No
                  other source is definitive.
                  I see now that my first understanding of the word 'scope' differs
                  from the strict meaning of the word 'scope' as defined in
                  .../ECMA-262.pdf :
                  If the word were strictly defined there, but your understanding does
                  appear to differ from the way the defined mechanism works.
                  'this' and 'scope' are still quite fuzzy for me.
                  Specific questions might get answered, but if you are looking for
                  someone to write out a detailed explanation for you then you can hope.
                  I greatly admire anyone, who in some seconds can reliably
                  see the correct interpretation of those, when looking at any
                  new code sequence.
                  It isn't difficult, the rules are simple.

                  Comment

                  • Jorge

                    #10
                    Re: simple variables as properties?

                    On Sep 4, 12:34 pm, Henry <rcornf...@rain drop.co.ukwrote :
                    >
                    'this' and 'scope' are still quite fuzzy for me.
                    >
                    Specific questions might get answered, but if you are looking for
                    someone to write out a detailed explanation for you then you can hope.
                    >
                    Leaving aside .apply() / .call() and new (Constructors), isn't it that
                    the simple rule to remember is that :

                    The value of 'this' is preset whenever a function is entered, and,
                    'this' is always preset to the global object *** except when/if the
                    function is called as an object's method *** ?

                    --
                    Jorge.

                    Comment

                    • Thomas 'PointedEars' Lahn

                      #11
                      Re: simple variables as properties?

                      Jorge wrote:
                      On Sep 4, 12:34 pm, Henry <rcornf...@rain drop.co.ukwrote :
                      >>'this' and 'scope' are still quite fuzzy for me.
                      >Specific questions might get answered, but if you are looking for
                      >someone to write out a detailed explanation for you then you can hope.
                      >
                      Leaving aside .apply() / .call() and new (Constructors), isn't it that
                      the simple rule to remember is that :
                      >
                      The value of 'this' is preset whenever a function is entered, and,
                      'this' is always preset to the global object *** except when/if the
                      function is called as an object's method *** ?
                      No, this would mean that the Global Object was not an object. It could also
                      mean that there were instances where `this' was not preset, which is not the
                      case as well (ES3F, 10.1.7 and 10.2.3).

                      If we ignored the cases that you mentioned, and also host objects, a simple
                      rule to remember could be that the `this' value refers to the calling
                      object; that is, the object on which the method was called.


                      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>

                      Comment

                      • Jorge

                        #12
                        Re: simple variables as properties?

                        On Sep 4, 2:40 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                        wrote:
                        Jorge wrote:
                        Leaving aside .apply() / .call() and new (Constructors), isn't it that
                        the simple rule to remember is that :
                        >
                        The value of 'this' is preset whenever a function is entered, and,
                        'this' is always preset to the global object *** except when/if the
                        function is called as an object's method *** ?
                        >
                        No, this would mean that the Global Object was not an object. It could also
                        mean that there were instances where `this' was not preset
                        Hmm, why ?

                        --
                        Jorge.

                        Comment

                        • Henry

                          #13
                          Re: simple variables as properties?

                          On Sep 4, 1:17 pm, Jorge wrote:
                          On Sep 4, 12:34 pm, Henry wrote:
                          >>'this' and 'scope' are still quite fuzzy for me.
                          >
                          >Specific questions might get answered, but if you are
                          >looking for someone to write out a detailed explanation
                          >for you then you can hope.
                          >
                          Leaving aside .apply() / .call() and new (Constructors),
                          isn't it that the simple rule to remember is that :
                          >
                          The value of 'this' is preset whenever a function is
                          entered, and, 'this' is always preset to the global
                          object *** except when/if the function is called as an
                          object's method *** ?
                          The rule is simple, but not quite as simple as that suggests. The
                          problem being that "called as an object's method" has little technical
                          meaning in terms of the specification.

                          You mean that when the item to the left of the parenthesise of what
                          may be called the 'call operator' is a property accessor then the
                          object that is the evaluated result of the part of the property
                          accessor prior to the final dot, or final set of brackets, becomes the
                          - this - value in the resulting function call. This would be true, but
                          is a little short of the whole picture.

                          Technically, when the right hand side of a CallExpression evaluates as
                          a Reference type and the - base - of that Reference type is non-null
                          and is not an 'Activation object' then that object becomes the value
                          used for - this - (else the global object is used instead). Property
                          accessors always evaluate to Reference types with non-null - base -
                          properties (or error, in which case you never get to the function call
                          question), but there are other possibilities.

                          Unless the process errors, Identifier resolution also always evaluates
                          to a Reference type. In those cases function local variables
                          (including a function's parameters and inner function declarations)
                          will result in a reference type with a Variable object as its - base
                          -, and as function execution contexts use their Activation object as
                          their Variable object those Reference types will not result in the -
                          base - being used for - this -. However, Identifier resolution can
                          happen within a - with - statement, and if the Identifier corresponds
                          with a named property of the object added to the scope chain with the
                          - with - statement then the Reference type will have the object added
                          to the scope chain as its - base -, and as that object is not an
                          Activation object it will become the - this - value for the function
                          call. To illustrate:-

                          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                          "http://www.w3.org/TR/html4/loose.dtd">
                          <html>
                          <head>
                          <title></title>
                          </head>
                          <body>
                          <script type="text/javascript">
                          (function(){
                          function test1(n){
                          alert(n+' test ='+this.exName) ;
                          }
                          with(
                          {
                          test2:test1,
                          exName:'Object added to scope chain.'
                          }
                          ){
                          test1('1'); //Expecting: '1 test =undefined'
                          test2('2'); //Expecting: '2 test =Object added to scope chain.'
                          }
                          })();
                          </script>
                          </body>
                          </html>

                          - where - test1 - and the - test2 - property of the object added to
                          the scope chain are the same function, and the code used in each call
                          has the same form/structure. Neither call looks like what could be
                          named a "method call", yet the - test2('2'); - call is setting the -
                          this - value to the object added to the scope chain, so it must be a
                          "method call" in some sense. And if - test('2'); - is a method call
                          then how can - test1('1'); - not be considered to be one? The
                          distinction certainly cannot be observed from the CallExpressions
                          themselves. The distinction, and so what must be the definition of a
                          "method call", is the value of a possible left hand side Reference
                          type and its - base -.

                          Comment

                          • Thomas 'PointedEars' Lahn

                            #14
                            Re: simple variables as properties?

                            Jorge wrote:
                            Thomas 'PointedEars' Lahn wrote:
                            >Jorge wrote:
                            >>Leaving aside .apply() / .call() and new (Constructors), isn't it that
                            >>the simple rule to remember is that :
                            >>The value of 'this' is preset whenever a function is entered, and,
                            >>'this' is always preset to the global object *** except when/if the
                            >>function is called as an object's method *** ?
                            >No, this would mean that the Global Object was not an object. It could also
                            >mean that there were instances where `this' was not preset
                            >
                            Hmm, why ?
                            If you are referring to my first sentence: See Richard's followup for
                            details. In short, it would mean that because globally declared functions
                            are methods of the Global Object (they become it per variable instantiation
                            of the global execution context where the Global Object is the Variable
                            Object). And they are called as such through the algorithm of "Identifier
                            and Scope Chain Resolution" (see ES3F) even when the Global Object is not
                            being referred to explicitly (per `this', or an expression that resolves to
                            a property to hold the reference, through that algorithm).

                            If you are referring to my second one: Because one could read your
                            statement-question as "The value of 'this' is preset whenever [something
                            applies] *** except when/if the function is called as an object's method ***".


                            HTH

                            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>

                            Comment

                            • Dr J R Stockton

                              #15
                              Re: simple variables as properties?

                              In comp.lang.javas cript message <c96a80e0-10d0-4d4f-9e6c-60139b328829@n3
                              8g2000prl.googl egroups.com>, Thu, 4 Sep 2008 03:34:08, Henry
                              <rcornford@rain drop.co.ukposte d:
                              >ECMA 262 (usually 3rd Ed (for now (3.1 is planed for next year))). No
                              >other source is definitive.
                              Not so. ISO/IEC 16262 is superior.

                              --
                              (c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
                              Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
                              Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                              Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)

                              Comment

                              Working...