Miscellaneous about javascript features

Source: Internet
Author: User

Recently, I learned a little crazy about the language, from Ruby to Lisp, and then C #. Now that I am crazy, I just want to learn javascript. the impression of javascript has been poor, from the users who have the most swear words to the most misunderstood language in the world, from the so-called crazy features, anything in the world that can be implemented using javascript will eventually be implemented by javascript, and this is the last implementation. there are too many sources, not to list them one by one. It is known to the insiders and it is not necessary to find the source for these boring remarks. in fact, javascript is not completely useless. I used javascript in Unity when I was developing a Unity project, but that javascript can only be called UnityScript. too many features implemented by myself, and some are incomplete. now, let's get to know the real javascript. mac OS X 10.8.2, node v0.8. 16. It should be explained that node is different from the javascript embedded in the browser and does not have interfaces like confirm and prompt. I use the console. log to output. javaScript itself is designed as a front-end language. It is said that it takes only 10 days to design. It has some defects, but it is indeed simple enough. although JavaScript The Definitive Guide is as thick as most language books, in fact, The introduction of The language itself is only about 200 pages, The thickness is actually similar to The C language described in R & D. this is because the design is relatively simple, and JavaScript is not regarded as a modern language and does not have some characteristics of modern language. optional statement Terminator for syntax details; this is rare. however, we recommend that you do not really save the standard. supports auto-increment ++ and auto-increment symbols. This is a habit of Ruby and Python. switch is similar to the traditional C language syntax, But it supports the case of strings. support for Na N, null, and undefined indicate similar meaningless quantities. Sometimes this is the root of chaos. infinity may be added. like most languages, javascript is also divided into Native and reference types. Native types are copied, parameters are passed, and comparisons are always passed through the value method, while the reference types are all referenced. the string is of an unchangeable type, and any change is processed to generate a new string. when compared, the value is compared. the string value is more natural than I personally think, and more natural than Java's abnormal method. you almost need to repeatedly tell every new programmer that the equals function is used to compare the string values in java. dynamic Language. variables are defined by var. the break and continue in label mode are supported. It is used to directly perform break and continue at the external layer in a multi-layer loop. A complete and traditional try, catch, and finally exception mechanism. except C ++'s lack of finally completeness, almost all The language exceptions are all designed in this way. although the syntax of string javascript is C-like, but the starting point is Java, although the designed object-oriented system is not a traditional template, the strings in javascript are all objects. "hello, world ". length // out: 12 the above Code is not uncommon now, but it is more advanced than C ++. (obviously C ++ lags behind) var str = "hello" + "," + "world! "; Console. log (str); // out: hello, world! The string supports the + operator to be connected as a string. the strange thing about javascript is that when strings and numbers are used simultaneously: console. log ("3" + 4 + 5); // out: 345console. log (4 + 5 + "3"); // out: 93 that is, strings are automatically converted to numbers in some languages (such as php, javascript tends to convert numbers into strings. in fact, this usage is too flexible. Even a language famous for its flexibility, Ruby and Python, does not allow such automatic type conversion. what's more strange is that this is not only true for addition, but also for multiplication: console. log ("3" * 4); // out: 12 console. log ("3" * "4"); // out: 12 in multiplication, because the javascript string is not like Ruby, python provides a special explanation for the multiplication operation (multiplication of strings indicates repetition). Therefore, strings are converted into Integers by default. What's more strange is that even two strings, no error is reported for Integer Conversion and calculation. function functions are the first type of values in javascript, and closures are also supported. this is the basis for javascript to form objects. function add (x, y) {return x + y;} var sub = function (x, y) {return x-y;} add (2, 3 ); sub (5, 3); // out: 5 // out: 2 has the above two function constructor forms, and there is no difference in calling. the first method is the same as the traditional function definition method, while the second method is actually the anonymous function definition method. however, because the function in javascript is the first type of value, it is very convenient to assign values. the anonymous function, also known as lambda, is a convenient and useful feature. With the support for closures, many features are derived. therefore, the features of javascript functional languages have been achieved. var caller = function (fun, leftParam, rightParam) {fun (leftParam, rightParam);} caller (function (a, B) {console. log (a + B) ;}, 10, 20); // out: 30 as shown in the preceding example, an important application of anonymous functions is to conveniently construct high-level functions. in the above example, the most common feature may be sorting, because there may be many sorting rules. Generally, the sorting function allows another function as a parameter, to specify the sorting rules. for example, in javascript, the ordinary sorting function is somewhat strange. By default, it is sorted by string. see the following example: a = [1, 3, 2, 10, 20]; console. log (. sort (); // out: [1, 10, 2, 20, 3] This is probably not what we want in most cases. By default, this is the first time I saw it, this is just as strange as adding strings and Integers to the end and changing them into strings. Maybe javascript is designed as a front-end validation form-based language, so it is so preferred for strings. fortunately, the sort function can still pass in a function as the sorting rule. see the following example: a = [1, 3, 2, 10, 20]; console. log (. sort (function (a, B) {return a-B;}); // out: [1, 2, 3, 10, 20] Because anonymous functions and recursion use more than general languages in javascript, arguments is provided. callee is used to represent the currently called function to facilitate the recursive call of anonymous functions. In fact, it is more suitable for DRY (Dont Repeat Yourself) than the recursive call of function names) principle, because when the function name is changed, you do not need to change the name of the function called recursively. var factorial = function (n) {if (n <= 1) {return 1;} else {return n * arguments. callee (n-1) ;}} factorial (4); // out: 24. More interestingly, arguments. callee is forbidden in the strict javascript mode. Simply put, this call method is not officially recommended and may be abolished in the future, mozilla's explanation is that this DRY use case itself is very "weak", but it stops inline optimization, because this method is implemented by referencing the un-inlined function, only when the un-inlined function is used, arguments. callee can be referenced. in fact, I think this is simply a waste of food because although it is implemented in this way, it is completely possible to perform Compiler optimization through better syntax analysis, instead of abandoning such useful syntax. this kind of usage is definitely not as "weak" as officially said. You must know that DRY is almost a top priority in the field of software design. A closure is a combination of a function and a range object in the created function. because of the powerful features and convenience of closures, many traditional languages are gradually added to their support. In many cases, it is even considered whether a language is a symbol of the times. function makeIncrementor (base) {var count = base; return function (num) {count + = num; return count ;}} obj1 = makeIncrementor (10 ); obj2 = makeIncrementor (20); obj1 (1); // out: 11obj1 (1); // out: 12 obj2 (2); // out: 22obj2 (2 ); // out: 24 the example above demonstrates the closure feature, which can obtain parameters and variables of upper-layer functions and are independent of each other, because the closure stores local states, it is often used as an object. flexible parameter call function add (x, y) {return x + y;} add (2, 3, 4); add (2); // out: 5 // out: NaN the above Code will not encounter errors during the call, but will directly discard the following parameters. even function calls with insufficient parameters will return NaN and no error will occur. this is essentially because when function call parameters are insufficient, the subsequent parameters are set to undefined. so although javascript does not support default parameters, it can be simulated. function mul (x, y) {if (y = undefined) {return x * 10;} return x * y;} mul (10); // out: 100 the more flexible syntax is to obtain parameters through the arguments variable, which supports any number of function parameters. function add () {var sum = 0; for (var I = 0, j = arguments. length; I <j; I ++) {sum + = arguments [I];} return sum;} add (2, 3, 4, 5); // out: 14 function-level scope javascript only has the function-level scope, and all functions are outside the global scope, with no block-level scope. this means that global variables are defined in blocks such as for, while, And if. this setting is against the day in modern languages. therefore, with the help of anonymous functions, people came up with a more strange solution to simulate block-level scopes. for (var I = 0; I <10; ++ I) {console. log (I);} console. log (I); // at this time, I is still available. (function () {for (var j = 0; j <10; ++ j) {console. log (j) ;}}) (); console. log (j); // ReferenceError: j is not defined. array javascript arrays are more flexible than imagined. They support adding elements with references that exceed the index. I have only seen them in ruby and php, but not even python. of course, although the design is flexible, it is easy to make obscure mistakes. In the end, it is hard to evaluate whether it is good or bad. a = [0, 1, 2]; a [. length] = 3;. push (4); console. log (a); // [0, 1, 2, 3, 4] the above two methods to add elements after an array are equivalent, if the added element is not the next element of the array (that is, skip addition), it will be filled with undefined in the middle. object javascript objects are essentially a set of hash tables. var obj = new Object (); var obj2 = {}; there are two types of syntax used to create an empty Object. The second is called the 'literal' syntax, it is also the basis of common data format Json. because it is a hash table, the content is added dynamically. var obj = new Object (); obj. name = "Simon"; obj. hello = function () {console. log ("hello," + this. name);} obj. hello (); // out: hello, Simon. some differences are that functions in javascript are the first type of values, so you can naturally add functions to this object to complete data encapsulation. using {} to initialize the above object makes it easier: var obj = {name: "Simon", hello: function () {console. log ("hello," + this. name) ;}} it is because the object is actually an associated array, so we can also use for in for traversal, the function is like the dir in python. similar to this kind of self-review function, it is scarce in traditional static languages. In that language, this function is called reflection. we also provide the typeof operator, hasOwnProperty, propertyIsEnumerable, and isPrototypeof functions. for (var name in obj) {console. log (name);} // out: name // out: hello. You can even use obj ["hello"] () this method is used to call functions in objects by associating arrays. object-oriented javascript is the first class-based (template-based) class definition method in the world except C ++, there are also popular languages similar to the prototype (prototype) of self language. although lua is prototype, it is only popular in game circles. custom object: function Rectangle (w, h) {this. width = w; this. height = h; this. area = function () {return this. width * this. height ;}} var rect1 = new Rectangle (2, 4); var rect2 = new Rectangle (8.5, 11); console. log (rect1.are (); // out: 8 the code above creates two Rectangle objects in a way similar to a constructor. note that the difference from the previous Object creation is that we used to build from the Object directly, so it is far less convenient to build multiple objects than this constructor method. with this method, we can get a simple method similar to the class-based object creation. only the constructor is created, not a class. however, the above Code is not perfect. The biggest problem is that each created object has its own area function. In fact, all objects only need to point to a common area function, this is also the practice of class-based languages such as C ++. create a function for each object, no matter whether it is run efficiency or memory usage efficiency. the solution provided by javascript is prototype. By default, a prototype variable is initialized in the function object. All functions in this variable will eventually be owned by the newly created object of this function, and all of them are references. See the code: function Rectangle (w, h) {this. width = w; this. height = h;} Rectangle. prototype. area = function () {return this. width * this. height ;}; var rect1 = new Rectangle (2, 4); console. log (rect1.are (); // out: Class Properties. In the class-based language, some attributes can be directly used by Class names, all objects in a class share the same object. in javascript, because all functions are objects and constructor is no exception, you can directly add attributes to the constructor to implement this feature. rectangle. UNIT = new Rectangle (1, 1); in fact, similar usage of javascript itself, such as Number. MAX_VALUE is such a class attribute. class Methods are the same as class attributes. When you create an object in the constructor, you can simulate Class Methods in the class-based language. I will not go into detail here. private Members is in the class-based language (except Python). Generally, different access permissions are set for different Members. for example, prvate, public, and protected of C ++. In javascript, the objects created in the preceding method can be viewed as public by default, but there is indeed a way to make the external access to internal variables. this method comes from JavaScript The Definitive Guide. The Code is as follows: function Rectangle (w, h) {this. getWidth = function () {return w;} this. getHeight = function () {return h ;}} Rectangle. prototype. area = function () {return this. getWidth () * this. getHeight () ;}var rect = new Rectangle (2, 3); console. log (rect. area (); // out: 6 at this time, the member variables can only be obtained through the access function (getWidth and getHeight), both outside the object and inside the object. the Crockford method actually does not fundamentally solve the problem. It only limits the need to access the function, and the external can still access the internal variables of the object. crckford is said to be the first Technology to discover how javascript creates real private variables. this technology is mainly described in Private Members in JavaScript. function Rectangle (w, h) {var width = w; var height = h; this. area = function () {return width * height;} var rect = new Rectangle (2, 3); console. log (rect. area (); this method utilizes the closure feature of javascript. In this case, width and height cannot be accessed externally. only internal functions can be accessed. similarly, private functions can also be implemented in the same way. However, I still feel that this method is not perfect because of the obvious reasons, in this case, all functions that need to access private variables can only be defined directly in the constructor, and prototype variables cannot be used any more. That is, each object mentioned above will have a new function problem. for details about how to simulate class-based Inheritance, see Douglas Crockford's Classical Inheritance in JavaScript. I personally dislike this strange method, so I don't want to use it here. if you really need class-based inheritance, you can find the real class you want in the latest javascript 2.0 standard (ECMAScript 5. although the relevant standards are still in progress, it may take several years to actually use them. the language development path is basically the same, and the program community has a more common standard. Therefore, PHP also adds complete object-oriented support in the new version, C ++ adds closures to the 11 standard. java and C # not only add closures in the new version, but also add templates. when javascript 2.0 is added to the class, it may be slightly different from C ++ in the future when javascript is used. it may be more like UnityScript. prototype-based inheritance this inheritance method is different from class-based inheritance. It directly uses the prototype feature of javascript. Before the real class does not come out, I personally like this method more. we can refer to the Douglas Crockford article. For more information, see Prototypal Inheritance in JavaScript. in simple words, the prototype variable is set as the parent class object to inherit. Based on the characteristics of javascript, when a function cannot be found, it will be searched in prototype, which is equivalent to directly using the function of the parent class when the subclass is not overloaded. when a function can be found, it directly uses the subclass function, which is equivalent to reloading the relevant functions of the parent class. because I still don't want to use this method, I will not describe it here. minimalism: This method was first seen in the network logs of Ruan Yifeng. For more information, see the three methods for defining classes in Javascript. according to Ruan Yifeng, this method was first proposed by the Dutch Gabor de Mooij in Object oriented programming in Javascript. this method does not use Object. the create and prototype features are essentially a new constructor defined by the user, simulating a prototype-like prototype mechanism. The code is relatively simple and easy to understand. however, it has already overturned all the content mentioned above in this section, such as not using prototype and new. class to create the above Rectange class, which can be implemented in the following way. var Rectangle = {createNew: function (w, h) {var rect = {}; rect. width = w; rect. height = h; rect. area = function () {return this. width * this. height ;}; return rect ;}} var rect = Rectangle. createNew (2, 3); console. log (rect. area (); It is important to note that the Rectangle is a simple object at this time, instead of a function (of course, it is actually an object) like the traditional method ). this is also an easy-to-understand advantage. then, we can create an object to be inherited in the createNew function of the subclass, and then modify the object until it meets our requirements. var SubRectangle = {createNew: function (w, h) {var rect = Rectangle. createNew (w, h); rect. perimeter = function () {return this. width * 2 + this. height * 2 ;}; return rect ;}} var rect = SubRectangle. createNew (2, 3); console. log (rect. area (); console. log (rect. perimeter (); Private member and class attributes I added the perimeter function in the new SubRectangle subclass for calculating the perimeter. We can see that the method used is very similar to the traditional inheritance. according to this idea and the traditional method mentioned above, the attributes of private variables and classes are very simple. var Rectangle = {createNew: function (w, h) {var rect ={}; var width = w; // private var height = h; // private rect. area = function () {return width * height;}; return rect ;}} Rectangle. UNIT = Rectangle. createNew (1, 1); // class propertie var rect = Rectangle. createNew (2, 3); console. log (rect. area (); console. log (Rectangle. UNIT. area (); the method of sharing functions is generally very simple, intuitive, and straightforward. There is no need to create more auxiliary functions like the Douglas Crockford method. however, just as the prototype solution is not used before, the member functions of each object are independent. If you are concerned about efficiency and memory, you can use the method of referencing external functions for optimization. var Rectangle = {_ area: function () {return this. width * this. height ;}, createNew: function (w, h) {var rect ={}; rect. width = w; rect. height = h; rect. area = Rectangle. _ area; return rect ;}} this method can solve the problem of multiple functions, but the problem is that private members cannot be accessed, and some interfaces are added to the external Rectangle, although the caller can be notified through naming, these interfaces are private. which method is used depends on efficiency or code design.

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.