JavaScript design patterns Chapter 1: Magic JavaScript (1)

Source: Internet
Author: User
JavaScript is a popular and widely used language in recent years. Because it is supported by almost all browsers, it has also been widely promoted. As a language, it becomes incredibly important in our lives, helping us enhance web functions and create rich user interfaces. Why some people still think SyntaxHighlighter. all ();

JavaScript is a popular and widely used language in recent years. Because it is supported by almost all browsers, it has also been widely promoted. As a language, it becomes incredibly important in our lives, helping us enhance web functions and create rich user interfaces.
Why are there still some people who think it is a "Toy" language and think it is not suitable for professional programmers. I think this is because they didn't realize its true power and its uniqueness over other programming languages. JavaScript is a very magical and advanced language with features not available in the C family.
In this chapter, we will explore what makes JavaScript so amazing. We will see that JavaScript allows you to do the same thing in a variety of different ways, and how to simulate the implementation of object-oriented programming through functional programming. We will discuss why you should put the design pattern on the homepage and how to use it to make your code more effective and work easier.

Flexible JavaScript
A very important feature of JavaScript is its flexibility. As a JavaScript programmer, you can make your program very simple or complex. JavaScript allows you to use different programming styles. You can use a functional style or an object-oriented programming style to write your code, similarly, you can write a relatively complex program without understanding functional or object-oriented programming. You can also use it by writing some simple functions. Or this is one reason some people regard JavaScript as a "Toy" language, but we should think that these are some excellent features. It allows programmers to master only a small subset of easy to learn languages to complete some useful functions, it also means that when you become a more advanced programmer, JavaScript will play a greater role in your hands.
JavaScript allows you to simulate patterns and ideas in other languages. In addition, it also contains some unique features. It provides the same object-oriented features as traditional server languages.
Let's take a look at several different code organization methods to complete the same task: Start and Stop an animation. It doesn't matter if you don't understand these examples. All the models and technologies we use here will be covered in this book. Now, you can use this section as an actual example of how JavaScript can accomplish the same task in different ways.
If you were a process-oriented programmer, you could do the following:

/* Start and stop animations using functions .*/
Function startAnimation (){

}
Function stopAnimation (){

}

This method is very simple, but it does not create an animation object so that you can save the state and have some methods that only apply to its internal state. The following code defines a class that allows you to create such an object:
/* Anim class .*/
Var Anim = function (){

};
Anim. prototype. start = function (){

};
Anim. prototype. stop = function (){

};
/* Usage .*/
Var myAnim = new Anim ();
MyAnim. start ();

MyAnim. stop ();

A class called Anim is defined here and two methods are added for the prototype attribute of this class. We will discuss this technology in detail in Chapter 3. If you like to create a class with only one declaration, you may write the following code:
/* Anim class, with a slightly different syntax for declaring methods .*/
Var Anim = function (){

};
Anim. prototype = {
Start: function (){

},

Stop: function (){

}
};

This looks a bit like the classic object-oriented programming style: nesting function declarations within a class declaration. If you have used this style before, you can try the following example. Do not worry if you do not understand the following code:
/* Add a method to the Function object that can be used to declare methods .*/
Function. prototype. method = function (name, fn ){
This. prototype [name] = fn;
};
/* Anim class, with methods created using a convenience method .*/
Var Anim = function (){

};
Anim. method (start, function (){

});
Anim. method (stop, function (){

});

Function. prototype. method allows you to add new methods to the class. It can receive two parameters: the first is the string used as the name of the new method, and the second is a function specified for this method name.
You Can slightly modify Function. prototype. method so that it can be called in a chain. To do this, you only need to return this when creating each method. We will discuss the link in Chapter 6th:
/* This version allows the cballs to be chained .*/
Function. prototype. method = function (name, fn ){
This. prototype [name] = fn;
Return this;
};
/* Anim class, with methods created using a convenience method and chaining .*/
Var Anim = function (){

};
Anim.
Method (start, function (){

}).
Method (stop, function (){

});

You just saw that we completed the same task in five slightly different ways. Depending on your programming background, you may feel that some method is better than others. This is actually good. JavaScript allows you to use the programming method that best suits your projects. Each method has different features and different code volumes, efficiency and performance. The first part of this book covers all of these programming methods.

A weak language
In JavaScript, you do not need to define a type when defining a variable, but this does not mean that it does not have a variable type. A variable can store data of multiple data types, depending on the data assigned to it. JavaScript has three basic data types: Boolean, numeric, and string (JavaScript, unlike other programming languages, uses integer and floating point types as the same type, it contains the function type of executable code and the Object type of the composite type (Array is a special Object that contains ordered data sets ). Now, it also has null and undefiend data types. The basic data type is passed by value. Other data types are passed by reference. Therefore, if you are not careful, unexpected problems may occur.
Like other weak-type languages, Variables change their data types based on their assigned values. The basic data types can be converted to each other. The toString method can convert a number or boolean data into a string. The parseFloat and floatInt functions can convert a string to a numeric type. A double negative number can convert a string or number to a boolean type.
Var bool = !! Num;
Variables of the weak type provide a lot of flexibility. You don't need to worry about data type errors, because JavaScript will automatically perform conversions when necessary.

Function is the first type object
In JavaScript, functions are first-class objects. It can be stored in a variable, passed into the function as a parameter, returned by the function as a return value, or dynamically constructed during running time. These features allow you to use functions to increase flexibility and performance. Later in this book, you will see that these features are the basis for building a traditional object-oriented framework.
You can use functiuon (){...} Method To create an anonymous function. It does not have a function name but can be assigned to a variable. The following is an example of an anonymous function:
/* An anonymous function, executed immediately .*/
(Function (){
Var foo = 10;
Var bar = 2;
Alert (foo * bar );
})();

This function is not assigned to any variables during definition and execution. The last pair of parentheses will immediately execute the function. But it must be written like this:
/* An anonymous function with arguments .*/
(Function (foo, bar ){
Alert (foo * bar );
}) (10, 2 );

This anonymous function is basically the same as the first one, but this function does not use var to internally define variables, but is passed into the function as a parameter, this function can return a value and be assigned to a variable.
/* An anonymous function that returns avalue .*/
Var baz = (function (foo, bar ){
Return foo * bar;
}) (10, 2 );
// Baz will equal 20.

One of the most interesting functions of an anonymous function is to create a closure. Closures create a variable protection space by using nested functions. JavaScript has a function-level scope, that is, variables defined in the function cannot be accessed externally. It also has a syntax scope, that is, the scope in which the function runs in their defined scope rather than the scope during their execution. The combination of the two allows you to create a protection variable through an anonymous function. You can use this to create private variables for the class.
/* An anonymous function used as aclosure .*/
Var baz;
(Function (){
Var foo = 10;
Var bar = 2;
Baz = function (){
Return foo * bar;
};
})();
Baz (); // baz can access foo and bar, even though it is executed outside of
// Anonymous function.

Variables foo and bar are defined only in anonymous functions. Because baz functions are also defined in this closure, they can access these two variables, even after the closure function is executed. This is a complex logic that we will always come into contact with throughout the book. We will explain this technology in detail when we discuss encapsulation in Chapter 3.

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.