Javascript, too, has betrayed the Revolution. (1)

Source: Internet
Author: User
Tags try catch
Update: I forgot to add an overview of the generic function. Just now. In addition, the leader of chenxiaoshun raised a very good question: What is the difference between generic function and function overloading? The difference is that the calling of the generic function is determined at runtime, consistent with the calling of the virtual function to achieve polymorphism. The overload function is determined during compilation. The supplementary content is that the generic function is used to solve such multi-allocation problems. When the generic function is called during running, the object is dispatched based on * All * parameters of the function. The general rule is that the more specific the type occupies, the higher the priority. For example, Foo (number) has a higher priority than Foo (object) Because number is a subclass of object and is more specific than object. In addition, the distribution weights of all parameters in the generic function are the same, which is called Symmetric Multi-distribution. Groovy uses Asymmetric Multi-allocation. The system first compares the first parameter. If you cannot decide, compare the second one... Two months ago. Today, however, we have a little leisure time and time to gossip. Javascript 2, which is the official review of ecmascript 4 (ES4). Yahoo! Douglas crockford is angry, because ES4 is really contrary to his hope that JavaScript will continue to be short and lean. In his words, ES4 is much larger than ES3, which can be tolerated. Rename, rename! The javascript family does not have this freak. Chris Wilson, ie's technical leader, is also angry. He believes that ES4 has added too many features and has changed the characteristics of JavaScript. Mozilla's cto, the main creation of JavaScript, Brendan eich will naturally not show weakness, tear down Wen liangmu's geek veil, use an open letter to high-profile accuse Microsoft, and then reply to geek's true nature, respond to technical questions with a wonderful lecture (the old guys using the Firefox + NoScript plug-in remember to temporarily allow the website, otherwise they will not see the effect of the slides ). By the way, run the question. We firmly oppose the translation of "geeks. Geek is a person with certain characteristics and has no relationship with his career or identity. Customer CC. This translation and the pseudo-Petty guys translate the home party into a "bang", which is no different from the "four or six. No, just calm down and think about whether "geeks" are just personal preferences. "Bang" to really crash. It does not matter, but it is clear that it is the land of old wealth and people who say they are buying, it is wrong. Of course, when I think of the translation of "code Daquan", which is pinned on the shame column, I feel at peace of mind. The javascript community is immediately divided into ES4, ES4, and wall-riding, like the mass movement set up by Zheng long. Robert scoble has always been crazy, throwing out an unreliable post, learning about the orange alarm of Bush before the election, and telling people to be careful about the Javascript split that leads to a new browser war, as a result, ES4 is essentially a superset of es3. Backward compatibility is one of es4. A few incompatible changes are not a big task, for example, prototype can run under es4. Microsoft continues to use es3. Where is the war? Besides, JavaScript has already been split. Javascript, JScript, actionscript, and openlaszlo JavaScript... The points of the dead. Politics is not an issue. Let's talk about ES4 itself. A word: full, full code. ES4 seems to include the popular features of Dynamic Language in the past 30 years. There are a lot of instance code in the White Paper, so I won't copy books here. Only some interesting features are listed monotonically.
  • Oop. ES4 adds interfaces and classes. Prototype + closure is used to simulate various types of OOP bosses. Familiar with the underground publications such as the object is just poor man's closure. In fact, I really welcome these features. Almost every popular framework should use simulated oop. The first piece of code written by programmers who do not need to use popular class libraries is mostly as follows:
// Makeclass-by John resig (MIT licensed)
FunctionMakeclass (){
Return Function (ARGs ){
If ( This InstanceofArguments. callee ) {
If ( Typeof This. Init = "function" )
This. Init. Apply ( This, ArgS. callee? ARGs: arguments );
} Else
Return NewArguments. callee (Arguments );
};
}In this case, why not support the highly repetitive work from the language level? It not only improves interoperability between codes, but also provides virtual machine-level optimization. Why should we simulate a class keyword with one, two, or even three-layer closure? Good, object is poor man's closure. But we can also say closure is poor man's object. More importantly, we YesFix or protect certain attributes. This cannot be achieved with the existing functions of ES3 (for example, the for .. in loop always traverses all attributes of the object class. We must manually filter ). ES4 supports common OOP functions:
    • Extends keywords are used for inheritance. Implement the interface using the implements keyword. Common keywords: static, final, and override. The boss familiar with Java and C # can laugh.

    • You can use the keyword dynamic to modify attributes in the class runtime. It supports getter and setter, so the bosses of Ruby and C # are excited. Keyword Meta is used to support method_missing () methods similar to Ruby. This is quite good. Many popular usage in ruby, especially the usage of DSL, can be used in handy.
    • Class attributes support three different modifiers: dontdelete: This attribute is fixed and cannot be dynamically removed; dontenum: This attribute will not appear in the for (var p in object) loop; and readonly: the value of this attribute is a constant. Once confirmed, this cannot be changed. The attributes of a common class are dontdelete and dontenum. The attributes of the dynamic class declared with dynamic class are neither dontdelete nor dontenum.
    • Generic function. That is, the common multimethod or multiple dispatch method. This is good news for those who are familiar with the c ++ operator overload, Clos and generic method in Dylan. Generic function is not a new concept. At the oopsla Conference in 1986, a group of Lisp hackers submitted the famous paper commonloops-merging lisp and object-oriented programming, which officially mentioned the term multimethod. According to Gregor kiczares, author of Clos (do elders who support AOP think they are very friendly ?) Recall that his collaborators Larry masinter first synthesized the word multimethod. Popular oo languages, such as Java/C #/C ++/Python/Ruby, usually only support single dispatch. That is to say, the method assignment is only related to the method caller or a certain parameter (such as the first parameter self in Python. When we see caller. Foo (), we know that the runtime calls the method Foo () in the object caller (). Unfortunately, the relationship in the real world is not that simple. Wikipedia uses collision as an example. When we want to implement collision between two types of objects, where can we implement our approach? For example, if we want a ship to collide with a meteorite, should we put the collide () method into spaceship or asteroid? What if we want to limit the collision category? For example, a friend's ship cannot collide, but can collide with an enemy's ship? What if we want multiple objects to collide? What should we do if we allow users of the Code to add new objects and the collision process after writing the code? The generic function is used to solve such multi-Dispatch Problems. When the generic function is called during running, the object is dispatched based on * All * parameters of the function. The general rule is that the more specific the type occupies, the higher the priority. For example, Foo (number) has a higher priority than Foo (object) Because number is a subclass of object and is more specific than object. In addition, the distribution weights of all parameters in the generic function are the same, which is called Symmetric Multi-distribution. Groovy uses Asymmetric Multi-allocation. The system first compares the first parameter. If you cannot decide, compare the second one...

      Let's look at a common visitor mode. We use a normal expression as an example.
      InterfaceVisitableexpression {
      Function accept (Visitor: expressionvisitor); // It is a drop. ES4 supports static type declaration.
      }

      ClassAddexpressionImplementsVisitableexpression {
      VaR lefoperand;
      VaR rightoperand;

      Function accept (Visitor: expressionvisitor ){
      Visitor. visitaddexpression (this );
      }
      }

      ClassIntexpressionImplementsVisitableexpression {
      VaR value;

      Function accept (Visitor: expressionvisitor ){
      Visitor. visitintexpression (this );
      }
      }

      InterfaceExpressionvisitor {
      Function visitaddexpression (expression: visitableexpression );
      Function visitintexpression (expression: visitableexpression );
      }

This Code contains many issues. It is easy to add a new visitor. For example, evaluate the visitor, print the visitor, or inject the visitor into the backdoor. But what about adding a new complexexpression? Every current visitor must be modified. If I want to change the signature of the expressionvisitor method, it would have been a wonderful thing, not a scandal caused by the stiff structure of visitableexpression. With the generic function, the visitor mode basically disappears:
Generic function evaluate (E); // generic function must declare generic function evaluate (E: addexpression ){...}
Generic function evaluate (E: intexpression ){...}

The evaluate here replaces the bloated class evaluatevisitor implements expressionvisitor. ES4 determines which evaluate () function is called based on the type of the evaluate parameter at run time. If a new expression, such as complexexpression, is added, you only need to add a function. Generic function evaluate (E: complexexpression) {...} Similarly, if we want to handle the collision problem:
Generic function Collide (a, B); generic function Collide (S: Spaceship, A: asteroid ){...}
Generic function Collide (F: friendspaceship, E: enemyspaceship ){...}
Generic function Collide (as: [asteroid], P: Planet) {...} // a pile of meteorite collision with the planet. It is no longer easy to add new objects and collision methods. Add a new generic function. You do not need to change any existing implementations.

The following is the test time. Use generic function to rewrite the following builder mode (the figure is taken from gof ):

The key is the convertxxx () method. After the method is rewritten using generic function, Builder/Director no longer needs it. The logic of convertxxx () is distributed to the fully orthogonal convert () function. It will be easy to add a new conversion method later. Generic function convert (token, tokentype, target); generic function convert (token: Token, type: Char, target: Tex ){...} Generic function convert (token: Token, type: font, target: Tex ){...}
Generic function convert (token: Token, type: Char, target: ASCII ){...}..... Using the generic function, we can also implement Operator overloading. For example, the addition of the overload complex: Generic intrinsic function + (A: complex, B: complex)
NewComplex (A. Real + B. Real, A. imag + B. IMAG)

Generic intrinsic function + (A: complex, B: anynumber)
A + complex (B)

Generic intrinsic function + (A: anynumber, B: complex)
Complex (A) + B the intrinsic here is the namespace built in ES4. Yes, ES4 introduces namespace, not only. Rather evil.

  • Type System. Of course, the classes and interfaces mentioned in OOP are also part of the type system (the so-called nominal type), but they are used too widely and they will be discussed separately.

    • Added the record and array types. {A: int, B: Char} is a record. [Int] is an integer array. Yes. ES4 introduces int and Char. It is no longer the same as before. Floating Point and string have everything to do. In addition, ES4 also introduces wrapper. For example, the wrapper of Boolean is Boolean, And the wrapper of double is double. I don't really understand this. Java distinguishes primitive from wrapper in terms of performance. Is this necessary for ES4?

    • Annotation. That is, the type statement we saw earlier. For example, var a: int; indicates a variable of the int type. Type Declaration is optional. You can add type annotations to function parameters, variable declarations, function return values, and constant declarations. This is no different from common static languages. This ensures that no type declaration code in ES3 is compatible with es4. Optional types support the so-called progressive development. We can start with a completely dynamic program and gradually add type declarations as the business model becomes stable. The type system during compilation also helps IDE development, compiler verification code, and document generation... There are many benefits.
    • Function type. Function (this: C, INT): Boolean indicates that the int parameter is accepted in class C and the Boolean function is returned. What is the purpose of this? When using ES3, we often pass anonymous functions.LightweightReplace the Strategy Mode. The problem is that all anonymous functions are of the same type: function. With the function type, we can limit acceptable functions. This is certainly favored by the Haskell/ml elders. However, when declaring the type, writing a long string is also self-abuse, so the type definition is shown in the following figure:
  • Type Definition. The type definition is similar to typedef in C/C ++. We use the keyword type to define the new type: Type intcomparator function (A: int, B: INT): Int. This Code defines a new function type intcomparator. If we write a sortint (intarray: [int], comparator: intcomparator) function for sorting integer arrays, you don't have to worry about accepting a function that compares strings. ES4 typedef is more powerful than C/C ++. Any Type Declaration defines the metadata of this type at the same time. Metadata implements the meta-object interface, which is read through reflection at runtime. At the same time, the defined types can be nested, but recursion (including interactive recursion) is not allowed ). For example, we define the type person: type person = {Name: {last: String, first: string}, born: date, spouse :*}. If spouse is of the person type, the ES4 environment is in an endless loop and consumes a large amount of memory. In the future, most compilers will report errors. Run.exe is the execution environment of es4.

    If there is a type, how can there be no subtype? S <: T indicates that type S is the child type of type T. The child type has a bunch of Judgment Rules. If you are interested, go to the 16th page of the White Paper. In addition, if there is a type, you must naturally consider the conversion between types. So there are two powerful keywords: Like (used to make the boss of Eifel laugh) and wrap. The keyword like is used to determine the type of weakening. It has a pattern matching style. You can declare var V: Like {X: int, Y: int }. Any value of the {int, int} type can be assigned to the variable v. For example, var p: point, then v = P is a valid value assignment statement. Like can also be used as an operator for trial. For example, {A: 10, B: 20} is like point will return true. This is like duck typing of data. Regardless of the value type, we only need to care about its "shape ". In this way, we can set the data structure, and do not have to be too limited by the data type. The keyword wrap is similar to like, but the variable type is forcibly "wrapped" to be compared. For example, in the following code, the variable V type is converted to the {X: int, Y: int} type:

    VaR V: Wrap {X: int, Y: int }={ X: 10, Y: 20}
    VaR W: {X: int, Y: int} = V

    When used as an operator, given two variables V and T, if v is t returns true, V wrap t returns the variable V, otherwise if V is like t is true, then a new object o is returned so that V is O is true. Otherwise, a typeerror exception is thrown. We can imagine that these two operators will derive many flexible applications. If you are interested, you can refer to more examples here.

  • Parametric types. That is, the type template we are talking about, or the generic type. For example, the following code creates a pair that can accommodate any type:ClassPair. <t> {
    VaR first: T, second: T
    }

    Functions, classes, interfaces, and types all support parameter types. Class can declare the function. Health problems arise. For example, in the following code, what is the type of variable X?


    ClassPair. <t> {
    VaR first: T, second: T;

    Function f. <t> (){
    VaR X: T;
    }
    }
    So we can use the type definition here:


    ClassPair. <t> {
    VaR first: T, second: T;

    Type XT = T;
    Function f. <t> (){
    VaR X: XT;
    }
    }

The following is a poem inserting: health issues are very important in languages that support macros. There is a special chapter in beautiful code to discuss it. It is strongly recommended.

I'm tired of reading the official website. It is because es4. ES4 introduces namespace management. If this parameter is left blank, the following parameters are used: Package, namespace, and program unit. In addition, ES4 includes list comprehension, Python-style iterator, and generator. Nullable type. Tail recursion optimization, Pragma, expression closure, destructive assignment, Java-style try catch, improved this, improved arguments parameters, improved with, and program running hook (meta-level hooks ), the & = and | = operators that I have long hoped for in private create the let expression of the local binding .... These are enough to write another post. Stay for the next time.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.