www.webdeveloper.com
Results 1 to 4 of 4

Thread: What is this syntax?

  1. #1
    Join Date
    Jul 2003
    Location
    UK
    Posts
    391

    What is this syntax?

    Hi,

    can someone explain this to me please:

    var myVar = function(){

    alert('');
    };

    Is this defining myVar as an object and function as a function of this object? Why is it defined in this way? Is function myVar() different?
    Thanks,

  2. #2
    Join Date
    Nov 2010
    Posts
    978
    not really. myVar is a variable and you are attaching an anonymous function to that variable. A function is always an object. It's kind of the same as function myVar(), but different. Have a look here for more detail.

  3. #3
    Join Date
    Jul 2003
    Location
    UK
    Posts
    391
    Thanks.

    How does it differ from this, and under what circumstances would you use it:

    var myVar = function myFunc(){

    alert('');
    };

    Also if you assigning or attaching as you said this function to that variable then is this variable now an object because a function is an object?

  4. #4
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,755
    The difference between:

    var foo = function() {};

    and

    function foo() {}

    Is that when the browser parses the JavaScript file, it will make functions declared as "function foo() {}" available before the actual script gets executed:
    Code:
    var x = 1;
    
    show(x);
    
    function show(x) {
      alert(x);
    }
    It would appear that the function call to "show" would result in an error, but does not. The browser created the "show" function before executing the "var x = 1" line of code.

    However:

    Code:
    var x = 1;
    
    show(x);
    
    var show = function(x) {
      alert(x);
    }
    Does result in an error because the function is defined as a variable after it was called.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles