Why myFunction function() {...}

Discussion in 'JavaScript' started by sugarland, May 20, 2009.

  1. #1
    I saw some people develop their functions in this way:

    I tried it myself, sometimes it's working, sometimes not. Why people create functions in the above style, and when it will be working?
     
    sugarland, May 20, 2009 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This syntax allows the creation of the so-called "objects" and is javascript's equivalent of OOP. It's commonly used in today's scripts, just as OOP is used in the programming languages. Take a look at my blog, most of the scripts are written as objects, maybe you will learn how and why it is used :)
     
    xlcho, May 20, 2009 IP
  3. samster7

    samster7 Banned

    Messages:
    170
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This way of defining a function looks very similar to the long way that use to define an object, array, or regular expression and the only way of defining other objects such as dates.

    In this way of defining javascript function content is passed as a literal in the last parameter to the call and is evaluated (the same as if it were in an eval statement) every time the statement is called.

    And also, all of the variables defined within this type of function definition are not restricted in scope to the function itself.
     
    samster7, May 20, 2009 IP
  4. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #4
    @sugarland: i started writing a guide to some of modern javascript's best practices a while back--even though I never got around to finishing it beyond functions and function interfaces. however, it does cover function constructs and assignments a fair bit, perhaps it may be of use to you. either way, you can always google for 'creating javascript functions' - plenty of examples out there.

    here's my unfinished article:
    http://fragged.org/javascript_best_practices.php
     
    dimitar christoff, May 21, 2009 IP
  5. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #5
    really? are you sure about that? don't think thats true at all.
    the only time eval takes place is when you use the class constructor varname = New function(evalString) - or so I thought, can you provide some evidence to the contrary?

    also, the scope of the variables defined within the function - can't possibly be global (unless not using 'var' to set them).
    can you demonstrate any of your statements this with a case study / example?
     
    dimitar christoff, May 21, 2009 IP
  6. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Variables are not global - each new object has it's own scope! In fact, this is an issue for most of the developers that learn how to write objects. Also, if you create a new object within a function or within another object - it is visible only in this function/object's scope.

    P.S. The this operator is very useful within the object. Learn how to use it. I've seen some guys trying to make something work with predefined arrays containing the names of the objects that they will create and then use this arrays and eval() to actually call something inside the objects... weird stuff :D

    Edit:
    Here is an example code:
    <script type='text/javascript'>
    function myFunc()
    {
    	this.text = 'blahblah';
    }
    
    obj = new myFunc();
    
    alert(text); //will not work - "text is not defined" error
    alert(obj.text); //will work
    </script>
    Code (markup):
     
    xlcho, May 21, 2009 IP
    dimitar christoff likes this.
  7. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #7
    @xlcho: не мога да се сетя за случаи, при които този eval е от полза... дай някакви примери? където и да съм чел за class constructor-а, винаги пише да се избягва, освен ако не е необходимо - само че без да покаже кога е това :(
     
    dimitar christoff, May 21, 2009 IP
  8. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Използват го за извикване на елементи от друг scope. Това има други начини да се направи, но хората го използват...

    На мен ми беше много удобно като писах едно калкулаторче на javascript. Проверявам си входните данни, т.е. дали е валидно уравнението. Примерно ако имам уравнение="23*4+16" директно правя eval(уравнение), т.е. оставям javascript-а да го сметне и директно да ми върне резултата :)

    По принцип и аз не виждам много къде му е ползата. Понякога с него лесно се заобикалят проблеми или дори е удобен (сега не мога да се сетя за други примери, но имаше и такива), но това е мноого рядко. С две думи - аз гледам да не го използвам :)
     
    xlcho, May 21, 2009 IP