Kung Fu: JavaScript style

    This article began as a comment on another article on habrahabr . After writing the first sheet, I realized the comment was too extensive :). I decided to write because I want to focus on points that, in my opinion, were missed. The limitation of this article is my goal to present everything as accessible as possible, do not look for mathematical accuracy in the definition of terms here, and yet I am enclosing links where mathematicians will find high-class definitions that are clear only to them :)

    Probably every article on JS is customary to start with words about its underestimation :) It's true :) When I said a couple of years ago that JS was my favorite language, they looked at me as a teenage schoolboy who just wrote his first page in HTML and those who knew me as a grandmaster who said that he only knows how the pieces go :). Such people did not become much smaller, alas :(

    So, the first point - nothing is said about how Javascript differs fundamentally from Java or C ++. The difference in the programming approach ( paradigm ) taken as a basis when creating the language. I do not evaluate “what better? ”, in no case, who is more comfortable :) or like :)


    The difference between the traditional class-object and the prototype paradigm


    Most people who look down on JS speak of him as if not OOP language :). To begin with, these are different things and they cannot be compared at all. Of course, you can program in JS using the skills acquired when programming in C ++ or Java, but it is not so effective. JS works differently, it has no classes, it has objects (don’t faint, read the article). This does not mean that it is not possible to do abstraction , encapsulation , inheritance, or polymorphism on JS . The main differences in the implementation of encapsulation , inheritance , and the work of the constructor. In JS, as in almost all prototype type languages, you need to use the term encapsulation , there isshort circuit .

    Short circuit


    I will notice that on habr already there was an article about closures . I’ll try to explain “on the fingers” and add an example.

    Closures in JS are the scope within which the variable makes sense :). It can be a definition of an object or function. A variable can be either primitive or an object or function. Phew ... now, darling, example:
    1. function bicubic(count)
    2. {
    3.   var values = [];
    4.  
    5.   for (var i = 0; i < count; i++)
    6.   {
    7.      values[i] = (
    8.          function(n)
    9.          {
    10.             return function()
    11.             {
    12.               return Math.pow(n, 3);
    13.             }
    14.          }
    15.      )(i);
    16.   }
    17.  
    18.   return values;
    19. }
    20.  
    21. var vals = bicubic(10);
    22.  
    23. alert( vals[3]() );
    * This source code was highlighted with Source Code Highlighter.
    If they showed me these lines and asked me to say “what the hell is this” I would spend more than one minute to figure it out :) This is exactly what makes the JS supporter so strong in the statement that class-based languages ​​lead to excessive code writing programmers focus on hierarchy and class connections with each other, which in my opinion is true.

    Let's take it in order :)
    1. The bicubic function is created which returns an array;
    2. The trick is that they are array members - these are functions without a parameter: Math.pow (n, 3). In this case, n, due to the closure miracle, becomes the value of i at the time of the passage of the cycle, and not after it!
    3. The magic in brackets (...) (i) is a function call with parameter i, and the definition of this function in brackets.

    because after passing through the cycle i = count, then without these brackets, we get a completely different answer - a constant 10'000, and with them 27.

    By the way, this technique is called breaking the closure.

    That is why jQuery recommends writing plugins for this framework inside the structure (... your plugin ...) ();, this allows you to:
    1. Write safe code
    2. Do not overload the browser with global variables

    Instance, constructor, object, and prototype


    So I recently wrote that in JS there are no classes, but there are objects. I had in mind the following:

    In class-oriented languages, a new instance is created through a call to the class constructor (possibly with a set of parameters). The resulting instance has a structure and behavior that are hard-coded by its class. Here are the lines from Wikipedia:
    In prototype-oriented systems (for example, JS), two methods are provided for creating a new object: cloning an existing object, or creating an object from scratch . To create an object from scratch, the programmer is provided with syntactic tools for adding properties and methods to the object. In the future, a complete copy of a clone can be obtained from the resulting object. In the process of cloning, a copy inherits all the characteristics of its prototype, but from then on it becomes independent and can be changed. In some implementations, copies store references to prototype objects, delegating part of their functionality to them; however, changing the prototype may affect all copies of it. In other implementations, new objects are completely independent of their prototypes.
    Demonstration:
    1. function win() {
    2.   this.open = function()
    3.   {
    4.      return "open 1";
    5.   }
    6. }
    7.  
    8. win.open = function() {
    9.   return "open 2";
    10. }
    11.  
    12. alert( win.open() ); // 1. open 2
    13.  
    14. win.prototype = {
    15.   save: function()
    16.   {
    17.      return "open 3";
    18.   }
    19. }
    20.  
    21. alert( win.save() ); // 2. error - нет save
    22.  
    23. win.prototype.open = function()
    24. {
    25.   return "open 4";
    26. }
    27.  
    28. alert( win.open() ); // 3. open 2
    29.  
    30. var vista = new win();
    31.  
    32. alert( vista.open() ); // 4. open 1
    33. alert( vista.save() ); // 5. open 3
    34.  
    35. vista.open = (
    36.   function()
    37.   {
    38.      return "open 5";
    39.   }
    40. )();
    41.  
    42. alert( vista.open ); // 6. open 5
    43.  
    44. alert( win.open() ); // 7. open 2
    * This source code was highlighted with Source Code Highlighter.

    “Open 4” we will not get, because the open method is defined in the object itself, which does not apply to save.

    The attentive reader will ask me - where is the constructor in this diabolical mixture? Yes, he was not here. The constructor is the object itself, it starts when the clone is created, using the new operator or initializing the object itself. Demonstration:
    1. function win()
    2. {
    3.   var str = "open 1";
    4.  
    5.   this.open = function()
    6.   {
    7.      return str;
    8.   }
    9. }
    10.  
    11. alert( (new win()).open() ); // open 1
    * This source code was highlighted with Source Code Highlighter.
    Creating an object from scratch in JS, “this thing”! I will give an example that helps to save the muscular efforts of the fingers:
    1. function plugin(options)
    2. {
    3.   options = options || {};
    4.  
    5.   options.list = options.list || [];
    6.  
    7.   // далее можно смело работать
    8.   // options, проверять его свойства, например,
    9.   // а с list как с массивом
    10. }
    * This source code was highlighted with Source Code Highlighter.


    Prototype, "inheritance" in javascript



    it is very difficult to find a black cat in a dark room, especially if it is not there :)
    © folk wisdom

    There is no inheritance in JS, much less plurality. Each object has a prototype, an object that can be shared among several objects or their instances, and then changed :)


    Total


    To the children praying for the OOP paradigm, wake up; there are many other programming paradigms. Not the best, there are the most suitable for certain tasks. JS is one of the languages ​​that have long occupied their niche, including because under it there is a very powerful foundation for the prototype programming paradigm .

    The rest, I hope I learned something useful :)

    Sincerely, Arthur Dudnik the
    most valuable human trait is the desire for self-improvement ©


    Also popular now: