Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference type and GetValue() [closed]

Tags:

javascript

Why if we run the following javascript code:

        var foo = {
           bar: function () {
               alert('s');
           }
       }

      //1. foo.bar();
      //2. var a = foo.bar;
      //3. var b = (foo.bar);          
       (foo.bar)();

we'll get an error message "foo is undefined", but if we uncomment 1. or 2. or 3. line we'll get alert 's'? I know that it's about Reference type and GetValue(), but I don't really understand the point.

Thanks

like image 939
Elistan Avatar asked Jun 12 '26 07:06

Elistan


1 Answers

It's because you don't have a semicolon before the (foo.bar).

This causes the (...) to be interpreted as a function call operator, so it's trying to invoke the previous expression as though it was a function.

  var foo = {
       bar: function () {
           alert('s');
       }
   }(foo.bar) // <-- It sees it like this

If you terminate the previous with a ;, it'll work.

   var foo = {
       bar: function () {
           alert('s');
       }
   }; // <--- right here

  //1. foo.bar();
  //2. var a = foo.bar;
  //3. var b = (foo.bar);          
   (foo.bar)();

So the reason it worked when the other lines were uncommented is that they are terminated.

If you want to exclude semicolons (which is what I do), you'll generally be safe if you follow these rules:

  • Never begin a new line with a ( unless you have a ; before it
  • Never begin a new line with a [ unless you have a ; before it

Whenever I start a line with one of those characters, I put a ; before it so I know the previous statement has been terminated.

like image 141
I Hate Lazy Avatar answered Jun 14 '26 20:06

I Hate Lazy