JavaScript Basic Optimization ("JavaScript advanced Programming" reading notes)

Source: Internet
Author: User

1. The <script> element with the SRC attribute should not contain additional JavaScript code between its <script> and </script> tags. If embedded code is included, only the external script file is downloaded and executed, and the embedded code is ignored. All JavaScript references are generally placed behind the page content in the <body> element.

2. Circular reference: Object A contains a pointer to object B, and object B also contains a reference to object a:

var element = document.getElementById ("some_element"); var New  == myObject;

Some of the objects in IE8 and previous versions are not native JavaScript objects, but are implemented using C + + in the form of COM (Component object model, Component object models) objects, while COM objects ' garbage
Collection mechanism because of the reference counting policy, there is a problem with circular referencing, which causes the memory leak to occur even if the DOM in the example is removed from the page and is never recycled. So once the data is no longer useful, it is best to release its reference by setting its value to null:

Nullnull;

3. Uninitialized variables are automatically assigned the undefined value, but it is still wise to initialize the variable explicitly, and when the typeof operator returns the "undefined" value, We know that the variable being detected has not been declared, not yet initialized.

4. Create object recommended combination using constructor mode and prototype mode:

functionPerson (name, age, job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. Friends = ["Shelby", "Court"];} Person.prototype={Constructor:person, sayname:function() {alert ( This. Name); }}varPerson1 =NewPerson ("Nicholas", "Software Engineer");varPerson2 =NewPerson ("Greg", "Doctor");p Erson1.friends.push ("Van"); alert (person1.friends); //"Shelby,count,van"alert (person2.friends);//"Shelby,count"Alert (person1.friends = = = Person2.friends);//falseAlert (Person1.sayname = = = Person2.sayname);//true

A combination of constructor patterns and prototype patterns in the constructor pattern is used to define instance properties, whereas the prototype pattern is used to define methods and shared properties.

Disadvantages of other modes:

Factory mode: Although it solves the problem of creating multiple similar objects, it does not solve the problem of object recognition (that is, how to know the type of an object);

Constructor Mode: Each method is recreated on each instance;

Prototype mode: All properties in the prototype are shared by many instances, which is appropriate for the function, but is problematic for properties that contain reference type values.

5. Inheritance in JavaScript can be inherited using combination (also known as pseudo-Classic inheritance):

functionsupertype (name) { This. Name =name;  This. colors = ["Red", "Blue", "green"];} SuperType.prototype.sayName=function() {alert ( This. name);};functionsubtype (name, age) {//Inheritance PropertiesSupertype.call ( This, name);  This. Age =Age ;}//Inheritance MethodSubtype.prototype =Newsupertype (); SubType.prototype.constructor=subtype; SubType.prototype.sayAge=function() {alert ( This. age);};varInstance1 =NewSubtype ("Nicholas", 29); Instance1.colors.push ("Black"); alert (instance1.colors); //"Red,blue,green,black"Instance1.sayname ();//"Nicholas";Instance1.sayage ();// invarInstance2 =NewSubtype ("Greg", 27); alert (instance2.colors); //"Red,blue,green"Instance2.sayname ();//"Greg";Instance2.sayage ();// -

Combined inheritance uses the prototype chain to implement the inheritance of the prototype properties and methods, by borrowing the constructor to implement the inheritance of the instance attributes, thus avoiding the defects of the prototype chain and borrowing the constructor. However, there is a lack of combinatorial inheritance, that is, in any case, the two-time superclass constructor is called: one time when creating a sub-type prototype (new Supertype ()) and the other within the subtype constructor (Supertype.call (this, name)). Parasitic combined inheritance overcomes this shortcoming, the basic pattern is as follows:

 function   object (o) { function   F () {} f.prototype  = o;  return  new   F ();}  function   Inheritprototype (subtype, supertype) { var  prototype = object (Supertype.prototype); //  Create object  prototype.constructor = subtype; //  enhanced object  Subtype.prototype = prototype; // } 

The so-called parasitic combined inheritance, that is, by borrowing the constructor to inherit the property, through the prototype chain of the hybrid form to inherit the method. The basic idea behind it is that you don't have to call a super-type constructor to specify a prototype of a subtype, all we need is a copy of the super-type prototype. Essentially, a parasitic inheritance is used to inherit a super-type prototype, and then the result is assigned to the child type's prototype. We can use the statement that calls the Inheritprototype () function to replace the statement in the previous example that assigns a subtype prototype, for example:

functionsupertype (name) { This. Name =name;  This. colors = ["Red", "Blue", "green"];} SuperType.prototype.sayName=function() {alert ( This. name);};functionsubtype (name, age) {Supertype.call ( This, name);  This. Age =Age ;} Inheritprototype (subtype, supertype); SubType.prototype.sayAge=function() {alert ( This. age);};

6, because of the problem of coupling, when writing recursive calls, using Arguments.callee is always more insurance than using the function name:

function factorial (num) {    if (num <= 1) {        return 1;     Else {        return// do not use return num * factorial (num-1);     }}

7. Because the closure carries the scope of the function that contains it, it consumes more memory than the other functions, and excessive use of closures can lead to excessive memory consumption.
8. Because JavaScript does not have block-level scopes, anonymous functions can be used to mimic block-level scopes:

(function() {    // This is a block-level scope });

This approach reduces the memory problems that are used by closures because there are no references to anonymous functions. This technique is also often used outside the function in the global scope to limit the addition of too many variables and functions to the global scope.

9, try not to use intermittent calls, because in the case of non-interference, intermittent calls will be carried out to the page unloading, and after a intermittent call may be started before the end of the previous intermittent call, it is best to use a timeout call to simulate intermittent calls, for example the next two pieces of code:

  intermittent call:  var  num = 0; var  max = 10 var  intervalid = ; function      Incrementnumber () {num  ++ //  if  (num == max) {Clearinterval (Inter        VALID);    Alert ( "Done" ); }}intervalid  = setinterval (Incrementnumber, n); 
Timeout call to simulate intermittent call: var num = 0; var max = ten; function Incrementnumber () {    num++    ; // set another timeout call if the number of executions does not reach the value set by Max    if (Num < max) {        $);     Else {        alert ("Done");     500);

10. To ensure cross-browser compatibility, it is best to compare the NodeType attribute to a numeric value because IE cannot access the Node type.

11. When using the CloneNode () method, it is a good idea to remove the event handler before copying, because IE has a bug where it replicates the event handlers.

12, minimize the number of visits to NodeList. Because every time you access NodeList, you run a document-based query.

13, because the old version of the browser is not supported, so when there is a special need to use event capture, you can confidently use event bubbling.

14. Because HTML is tightly coupled with JavaScript code, do not use HTML event handlers, and you can use JavaScript to specify event handlers.

15. Use event delegates to add an event handler at the highest possible level in the DOM tree, without having to add an event handler for each of the elements that can be clicked, because event delegation takes advantage of event bubbling and specifies only one event handler to manage all events of a certain type. The most appropriate events for using Event delegation technology include Click, MouseDown, MouseUp, KeyDown, KeyUp, and KeyPress.

16. When you submit a form by calling the Submit () method, the Submit event is not triggered, so remember to validate the form data before calling this method. Unlike calling the Submit () method, calling the Reset () method triggers the reset event just like clicking the Reset button.

17. It is not recommended to use the standard DOM method when reading or setting the value of a text box, but instead using the Value property:

var textbox = document.forms[0].elements["TextBox1"= "Some new value";

In other words, do not use SetAttribute () to set the value attribute of the <input> element, nor to modify the first child node of the <textarea> element. The reason is simple: modifications made to the Value property are not necessarily reflected in the DOM. Therefore, it is best not to use DOM methods when working with the value of a text box.

18. It is not recommended to use the regular DOM functionality to access the option element's data because it is less efficient, preferably with option-specific properties, because all browsers support these properties:

var selectbox = document.forms[0].elements["Location"]; // Not recommended var // text of the option var // The value of the option // Recommended var // text of the option var // The value of the option

JavaScript Basic Optimization ("JavaScript advanced Programming" reading notes)

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.