One of object-oriented Javascript (originally known as Javascript) _ js object-oriented

Source: Internet
Author: User
Javascript is an expressive language that plays a key role in today's popular Web wave. The rational and efficient use of this technology can make our Web world colorful. First, let's take a look at several unique features of this technology. 1. The biggest feature of Javascript is its flexibility. As a front-end developer, you can either adopt a functional programming style or a more complex object-oriented programming style. No matter which style you adopt, you can complete some very useful tasks. Therefore, Javascript is a process-oriented language and also an object-oriented language, which can imitate the programming mode and usage of the object-oriented language. We use an example to describe how to start and stop an animation.

If you are used to functional programming, the code will be as follows:

The Code is as follows:


Function startAnimation (){
// Enable Animation
}
Function stopAnimation (){
// Stop the animation
}


This method is simple, but you cannot create an animation object that saves the status and only operates on the internal status. The following defines a class:

The Code is as follows:


Var Animation = function (){
// Animation
};
Animation. prototype. start = function (){
// Enable Animation
};
Animation. prototype. stop = function (){
// Stop the animation
};
/* Usage */
Var anim = new Animation ();
Anim. start ();
Anim. stop ();


If you want to encapsulate the class definition in a declaration, the Code is as follows:

The Code is as follows:


Var Animation = function (){
// Animation
};
Animation. prototype = {
Start: function (){
// Enable Animation
},
Stop: function (){
// Stop the animation
}
};


In this way, the object-oriented programmers will become more familiar. We can try to write more complex statements:

The Code is as follows:


Function. prototype. method = function (name, fn ){
This. prototype [name] = fn;
}
Var Animation = function (){
// Animation
};
Animation. method ("start", function (){
// Enable Animation
});
Animation. method ("stop", function (){
// Stop the animation
});


We have extended a method for the Function class to add a new method. Name indicates the function name, and fn indicates the specific implementation of the function. Based on this writing method, we can allow functions to support chained calls:

The Code is as follows:


Function. prototype. method = function (name, fn ){
This. prototype [name] = fn;
Return this;
}
Var Animation = function (){
// Animation
};
Animation. method ("start", function (){
// Enable Animation
}). Method ("stop", function (){
// Stop the animation
});


So far, we have seen five different programming styles with different code volumes, encoding efficiency, and execution performance. You can select the programming style that best suits your current project.

2. Javascript is a weak language. You do not need to specify a type when declaring a variable, but it does not mean that there is no type. Javascript contains three basic types: Boolean, numeric, and string. In addition, it also contains object and function types, and finally contains null and undefined types. The basic type is passed by value, and Other types are passed by reference. You can change the type based on the value assignment of the variable. The basic types can be converted to each other. ToString () can convert a value or Boolean value to a string. parseInt () and parseFloat () can convert a string to a value, A double "Non" operation can convert a string or value to a Boolean value.

3. Javascript Functions are "First Class" objects. Functions can be stored in variables, transmitted as parameters to other functions, transmitted from other functions as return values, or constructed at runtime. It brings great flexibility and expressive ability when dealing with functions. These are the basis for building object-oriented systems. You can use function () {...} to create an anonymous function (no function name or variable ). The following is an example:

The Code is as follows:


(Function (){
Var a = 10;
Var B = 5;
Alert (a * B); // return 50
}) (); // The function definition is executed immediately.


The reason for immediate execution is a pair of parentheses after the function declaration. However, we found that there was nothing in the brackets.

The Code is as follows:


(Function (a, B ){
Alert (a * B); // return 50
}) (10, 5); // is equivalent to the preceding


This anonymous function is equivalent to the previous one, except that the variable is not declared in the function, but directly passed in from the external. In fact, this anonymous function can also return a value and assign it to a variable.

The Code is as follows:


Var c = (function (a, B ){
Return a * B; // return 50
}) (10, 5); // is equivalent to the preceding
Alert (c); // 50


The maximum purpose of an anonymous function is to create a closure. A closure is a protected variable space generated by nested functions. Because Javascript has a function-level scope, that is, variables defined inside the function cannot be accessed outside the function, and the function only runs in the scope that defines it, instead of in the scope of the call. In this way, variables can be wrapped in anonymous functions for protection. For example, you can create a private variable in the following ways:

The Code is as follows:


Var c;
(Function (){
Var a = 10;
Var B = 5;
C = function (){
Return a * B; // return 50
}
})();
C (); // c can access a and B, even if it can be executed outside the anonymous Function


4. Javascript objects are "easy to change. Everything is an object (except for three basic types), and all objects are changeable. This means that you can use technologies that do not exist in other languages. For example, add attributes dynamically for a function.

The Code is as follows:


Function displayError (error ){
DisplayError. numTimesExecuted ++;
Alert (error );
}
DisplayError. numTimesExecuted = 0; // indicates that you can modify the pre-defined classes and objects.


You can use the prototype mechanism to dynamically Add a class instance after it is created. This is still valid for the defined object. For example:

The Code is as follows:


Function Person (name, age ){
This. name = name;
This. age = age;
}
Person. prototype = {
GetName: function (){
Return this. name;
},
GetAge: function (){
Return this. age;
}
};
// Define two variables first
Var miracle = new Person ("Miracle", 28 );
Var mike = new Person ("Mike", 32 );
// Add a method dynamically
Person. prototype. getGreeting = function (){
Return "Hello" + this. getName () + "! ";
};
// DisplayGreeting () is only valid for Miracle
Miracle. displayGreeting = function (){
Alert (this. getGreeting ());
}


Reflection (also known as "Introspection") is related to object variability, that is, checking object attributes and methods at runtime, and using this information to instantiate classes and execution methods, you do not even need to know their names during development. With these two features of objects, you can completely imitate the advanced features of object-oriented languages, but remember that any object in Javascript can be modified at runtime.

5. Javascript has the Tianji that implements "inheritance. Javascript inheritance includes class inheritance and Object-based original type inheritance. This topic will be discussed in detail in the next article.

Finally, what are the advantages of using object-oriented and design patterns to deal with Javascript, a seemingly Procedural language? I have summarized the following points for your reference:

(1). maintainability. This helps to reduce the coupling between modules. Code in the project can be divided by module and function responsibilities.

(2). Easy to communicate. For a large team, it may be possible to use a very simple design pattern to give a high-level picture of the functional modules you are responsible for implementing, without having to let other team members focus too much on the details.

(3). improve performance. The mode can reduce the amount of code transferred to the client and increase the speed of running the program.

Of course, there are advantages and disadvantages. Disadvantages:

(1). Relatively high complexity. The cost of obtaining maintainability is divided by code highly refactoring and modularity. For some new users, it is difficult to adapt.

(2). Some modes reduce performance. However, this drag-and-drop is dependent on your project needs and may be insignificant and sometimes unacceptable.

Therefore, we recommend that you learn how to understand the application scenarios of the design model. Blind application and error scenarios are misuse.
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.