Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Nov 2012
    Posts
    11
    Thanks
    3
    Thanked 0 Times in 0 Posts

    undefined expected but getting false

    Hi All,

    I am new to JS and the web dev in general. I am coming from background of C++ and Java. Below is a piece of code which confuses me and i want your opinions into why it works as its working now

    Code:
    var aVar = {
            not:function()
                    {return !this.tVar},
            tVar:true
    }
    
    function chkChk() {
           document.write(aVar.not()); //false
           document.write(aVar.b);  // undefined
    }

    Now, in the above code i have been told that aVar.not() should result in undefined and my logic also says soo because the function not returns tVar which is initialized to true after the not function.
    But, the problem is it returns false. Why ??

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    One thing you seem to misunderstand here:

    tVar: true is not really an assignment operation, it is rather a definition of a key/value pair inside an object literal. Key/Value pairs in object literals do not have an order! So once you defined the object literal like that, all of its key/value pairs are defined and if you access tVar from another key ("not()" in your case), tVar will be true.

  • #3
    New Coder
    Join Date
    Nov 2012
    Posts
    11
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Hmm, So i guess i have been told incorrectly that aVar.not() results in undefined. Can you also please tell me what does 'this' refers to in the above context. Does it refer to aVar ??

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    Yes, it refers to the current object which is aVar.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    It's really not different than, say, a C++ class:
    Code:
    class aClass {
      public:
        bool not() { return ! this.tVar; }
      private:
        bool tVar = true;
    }
    
    aClass aVar = new aClass( );
    except that the class declaration *AND* the instantiation of an instance thereof are combined. Hence the name "object literal". See the parallel to "string literal", an example of which would be just "this is a string literal".

    In JavaScript, since there are no classes, we could create an [b]aVar[b] object this:
    Code:
    // constructor for an oVar object:
    function oVar( )
    {
        this.tVar = true;
    
        function not( ) { return ! this.tVar; }
    }
    
    var aVar = new oVar( );
    And that works just fine. But it's essentially identical to the object literal
    Code:
    var aVar = {
            not : function() {return !this.tVar},
            tVar : true
    };
    By the by, you could also write that as:
    Code:
    var aVar = {
            "not" : function() {return !this.tVar},
            "tVar" : true
    };
    and you could invoke either
    Code:
        aVar.not( );
    or
        aVar["not"]( );
    or
        var foo = "no";
        aVar[foo + "t"]( );
    100% equivalently. Do you begin to see some possibilities?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    salmanmanekia (11-10-2012)

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Forgot to say: One good reason to use a constructor instead of an object literal is obvious by example:

    Code:
    function oVar( init )
    {
        this.tVar = init;
    
        function not( ) { return ! this.tVar; }
    }
    With a constructor, you are getting much closer to C++/Java style constructors, wherein you can pass in values for initialization.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,248
    Thanks
    12
    Thanked 340 Times in 336 Posts
    On the other hand side, object literals are Singletons (should you need one).
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Well, sure.

    But I think that comes naturally.

    In JavaScript, as in most modern languages (including C++, Java, C#, etc.), variables contain *references* to objects, not the actual objects [okay, I know there is a way to make an exception to this in C++].

    So if you do
    Code:
    var aVar = { xxx : yyy, zzz: aaa };
    then of course is you later do bVar = aVar; you are only copying the *reference*. The object remains unchanged. There's no way to have another one of this same object.

    But, yes, it's an interesting design pattern. Not sure how useful it is to think of it as a singleton, but it is.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,248
    Thanks
    12
    Thanked 340 Times in 336 Posts
    Quote Originally Posted by Old Pedant View Post
    Not sure how useful it is to think of it as a singleton, but it is.
    It fulfills the objective of a Singleton as to "only allow one single instance". That it looks different from what we’re used to in class-based languages doesn’t matter. Another way for a Singleton is the Module pattern, which, incidentally (though with a slightly different intend), also uses an object literal for that purpose.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Sorry...I just meant that you don't need to know the term "singleton" to realize that each object literal must be uniquely itself. So a JS programmer wouldn't need to think of it as "singleton" if the term doesn't mean much to him/her.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,618
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Old Pedant View Post
    Sorry...I just meant that you don't need to know the term "singleton" to realize that each object literal must be uniquely itself. So a JS programmer wouldn't need to think of it as "singleton" if the term doesn't mean much to him/her.
    By the definition of what a singleton is that is used in object oriented languages, all objects in JavaScript are singletons because there are no classes.

    You can copy objects in JavaScript - just not using a simple assignment.

    Code:
    deepCopy = function(p,c) {
    var c = c||{};
    for (var i in p) {
      if ('object' === typeof p[i]) {
        c[i] = (p[i].constructor === Array)?[]:{};
        deepCopy(p[i],c[i]);
      } else c[i] = p[i];}
    return c;
    }
     
    bVar = deepCopy(aVar);
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Agreed. Technically, all JS objects are singletons. But it's not very useful to think of them that way if, for example, they were created via a constructor.

    And in most class-oriented languages, a singleton pattern means one in which you can NOT create more than one object of the given class. By that pattern (not by that definition), no constructor-based object in JS is a singleton.

    So it's really a matter of how you want to view things and whether it really matters if you relate JS to other languages.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,248
    Thanks
    12
    Thanked 340 Times in 336 Posts
    Quote Originally Posted by felgall View Post
    By the definition of what a singleton is that is used in object oriented languages, all objects in JavaScript are singletons because there are no classes.
    I’m with Old Pedant here. I no definition of Singleton that I know is the term "classes" included. I always read about instances of objects.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,618
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Old Pedant View Post
    Agreed. Technically, all JS objects are singletons. But it's not very useful to think of them that way
    I agree - that's why my JavaScript course includes the following code as a way to create in JavaScript what most people actually intend when they refer to a singleton:

    Code:
    single = function(x) {
      single.only = function() {
        if (typeof one_only === 'undefined') one_only = this;
        };
      single.only();
      one_only.a = x;
      return one_only;
    }
     
    t1 = new single(1);
    t2 = new single(2);
    which results in t1 and t2 both pointing to the same 'singleton' object.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Cute. But it does require one_only as page scope variable, so if you have a few different singletons on the page presumably you'd want a longer name with each and one not likely to collide. I do like the concept!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •