1. The biggest feature of Javascript is its flexibility. As a front-end developer, you can adopt both a functional programming style or a more complex object-oriented programming style. No matter what style you adopt, you can accomplish some very useful tasks. Therefore, Javascript is a process-oriented language and an object-oriented language, which can then imitate the programming patterns and idioms of object-oriented languages. Let's use an example to illustrate: start and stop animation.
If you are used to functional programming styles, the code will be as follows:
function startAnimation() {
//Enable animation
}
function stopAnimation() {
//Stop the animation
}
This method is simple, but it is impossible to create animated objects that save states and operate only on internal states. Here we define a class:
var Animation = function() {
//Animation
};
= function() {
//Enable animation
};
= function() {
//Stop the animation
};
/*Usage is as follows*/
var anim = new Animation();
();
();
If you want to encapsulate the definition of a class into a declaration, the code is as follows:
var Animation = function() {
//Animation
};
= {
start: function(){
//Enable animation
},
stop: function(){
//Stop the animation
}
};
This makes object-oriented programmers look more familiar, and we can try to try more complicated writing methods:
= function(name, fn){
[name] = fn;
}
var Animation = function() {
//Animation
};
("start", function(){
//Enable animation
});
("stop", function(){
//Stop the animation
});
We have extended a method method for the Function class to add new methods. name represents the function name, and fn represents the specific implementation of the function. Based on this writing method, we can make the function support chain calls:
= function(name, fn){
[name] = fn;
return this;
}
var Animation = function() {
//Animation
};
("start", function(){
//Enable animation
}).method("stop", function(){
//Stop the animation
});
So far, we have seen 5 different programming styles, with different code volume, coding efficiency and execution performance. You can choose the programming style that best suits the current project to work.
2. Javascript is a weak language. You do not have to specify a type when declaring a variable, but it does not mean there is no type. Javascript contains three basic types: boolean, numeric, and string types, in addition to object and function types, and finally empty and undefined types. The basic types are passed by value, and other types are passed by reference. Types can be changed according to the assignment of variables, and basic types can be converted to each other. toString() can convert numeric or boolean values into strings, parseInt() and parseFloat() can convert strings into numeric values, and double "non" operations can convert strings or values into boolean values.
3. Javascript functions are "first class" objects. Functions can be stored in variables, passed as parameters to other functions, passed as return values from other functions, or constructed at runtime. When dealing with functions, it brings great flexibility and strong expression capabilities, which are the basis for building object-oriented. Anonymous functions can be created through function() {...} (without function names, they can also be assigned to variables). The following is an example:
(function(){
var a = 10;
var b = 5;
alert(a * b);//Return 50
})();//The function definition is executed immediately
The reason why it can be executed immediately is because of a pair of brackets after the function declaration. But we found that there is nothing in the brackets, and that is not exactly the case.
(function(a, b){
alert(a * b);//Return 50
})(10, 5);//Equivalent to the previous one
This anonymous function is equivalent to the previous one, but the variable is not declared within the function, but is passed directly from the outside. In fact, this anonymous function can also have a return value and assign it to a certain variable.
var c = (function(a, b){
return a * b;//Return 50
})(10, 5);//Equivalent to the previous one
alert(c);//50
The biggest use of anonymous functions is to create closures. The so-called closure is a protected variable space generated by an embedded function. Since Javascript has a function-level scope, that is, variables defined inside a function cannot be accessed outside the function, the function only runs in the scope that defines it, not in the scope of the call. In this way, variables can be wrapped in anonymous functions for protection. For example, you can create private variables in the following ways:
var c;
(function(){
var a = 10;
var b = 5;
c = function(){
return a * b;//Return 50
}
})();
c();//c can access a,b, and it can be executed even if it is outside the anonymous function
4. Javascript objects are "mutable". Everything is an object (except 3 basic types), and all objects are mutable. This means you can use some technology that does not exist in other languages. For example, dynamically add properties to functions.
function displayError(error){
++;
alert(error);
}
= 0;// means that predefined classes and objects can be modified
You can use the prototype mechanism to dynamically add the class instance after it is created, and it is still valid for defined objects. For example:
function Person(name, age) {
= name;
= age;
}
= {
getName: function() {
return ;
},
getAge: function() {
return ;
}
};
//Define two variables first
var miracle = new Person("Miracle", 28);
var mike = new Person("Mike", 32);
// Dynamically add a method
= function() {
return "Hello " + () + "!";
};
//displayGreeting() is only valid for Miracle
= function() {
alert(());
}
Related to object volatility is reflection (also known as "introduction"), which means checking the properties and methods of objects at runtime and using this information to instantiate classes and execute methods, and even without knowing their names during development. With these two major features of objects, you can completely imitate the advanced features of object-oriented languages, but remember that in Javascript any object can be modified at runtime.
5. Javascript has the talent to implement "inheritance". Let me briefly mention it here: Javascript inheritance includes "classical" inheritance and object-based prototype inheritance. I will discuss this topic in detail in the next issue of the article.
Finally, let’s summarize, what are the benefits 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. It helps to reduce coupling between modules, and the code in the project can be divided by module and functional responsibilities.
(2). Easy to communicate. For a large team, it may be possible to highly summarize the functional modules you are responsible for in terms of simple design patterns without having to pay too much attention to the details of the rest of the team.
(3). Improve performance. Utilization mode can reduce the amount of code transmitted to the client while increasing the speed of program operation.
Of course, there are advantages and disadvantages. The disadvantages are:
(1). The complexity is relatively high. The cost of obtaining maintainability is based on the highly refactoring and modular division of the code, which is difficult for some newbies to adapt to.
(2). Some modes reduce performance instead. But this drag depends on your project needs, and may sometimes be trivial and sometimes difficult to accept.
Therefore, it is recommended that everyone learn to understand the application scenarios of design patterns. Using the right scene is the true application of the design patterns. Blindly applying and using the wrong scenario is misuse, and it is better not to use it.
If you are used to functional programming styles, the code will be as follows:
Copy the codeThe code is as follows:
function startAnimation() {
//Enable animation
}
function stopAnimation() {
//Stop the animation
}
This method is simple, but it is impossible to create animated objects that save states and operate only on internal states. Here we define a class:
Copy the codeThe code is as follows:
var Animation = function() {
//Animation
};
= function() {
//Enable animation
};
= function() {
//Stop the animation
};
/*Usage is as follows*/
var anim = new Animation();
();
();
If you want to encapsulate the definition of a class into a declaration, the code is as follows:
Copy the codeThe code is as follows:
var Animation = function() {
//Animation
};
= {
start: function(){
//Enable animation
},
stop: function(){
//Stop the animation
}
};
This makes object-oriented programmers look more familiar, and we can try to try more complicated writing methods:
Copy the codeThe code is as follows:
= function(name, fn){
[name] = fn;
}
var Animation = function() {
//Animation
};
("start", function(){
//Enable animation
});
("stop", function(){
//Stop the animation
});
We have extended a method method for the Function class to add new methods. name represents the function name, and fn represents the specific implementation of the function. Based on this writing method, we can make the function support chain calls:
Copy the codeThe code is as follows:
= function(name, fn){
[name] = fn;
return this;
}
var Animation = function() {
//Animation
};
("start", function(){
//Enable animation
}).method("stop", function(){
//Stop the animation
});
So far, we have seen 5 different programming styles, with different code volume, coding efficiency and execution performance. You can choose the programming style that best suits the current project to work.
2. Javascript is a weak language. You do not have to specify a type when declaring a variable, but it does not mean there is no type. Javascript contains three basic types: boolean, numeric, and string types, in addition to object and function types, and finally empty and undefined types. The basic types are passed by value, and other types are passed by reference. Types can be changed according to the assignment of variables, and basic types can be converted to each other. toString() can convert numeric or boolean values into strings, parseInt() and parseFloat() can convert strings into numeric values, and double "non" operations can convert strings or values into boolean values.
3. Javascript functions are "first class" objects. Functions can be stored in variables, passed as parameters to other functions, passed as return values from other functions, or constructed at runtime. When dealing with functions, it brings great flexibility and strong expression capabilities, which are the basis for building object-oriented. Anonymous functions can be created through function() {...} (without function names, they can also be assigned to variables). The following is an example:
Copy the codeThe code is as follows:
(function(){
var a = 10;
var b = 5;
alert(a * b);//Return 50
})();//The function definition is executed immediately
The reason why it can be executed immediately is because of a pair of brackets after the function declaration. But we found that there is nothing in the brackets, and that is not exactly the case.
Copy the codeThe code is as follows:
(function(a, b){
alert(a * b);//Return 50
})(10, 5);//Equivalent to the previous one
This anonymous function is equivalent to the previous one, but the variable is not declared within the function, but is passed directly from the outside. In fact, this anonymous function can also have a return value and assign it to a certain variable.
Copy the codeThe code is as follows:
var c = (function(a, b){
return a * b;//Return 50
})(10, 5);//Equivalent to the previous one
alert(c);//50
The biggest use of anonymous functions is to create closures. The so-called closure is a protected variable space generated by an embedded function. Since Javascript has a function-level scope, that is, variables defined inside a function cannot be accessed outside the function, the function only runs in the scope that defines it, not in the scope of the call. In this way, variables can be wrapped in anonymous functions for protection. For example, you can create private variables in the following ways:
Copy the codeThe 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,b, and it can be executed even if it is outside the anonymous function
4. Javascript objects are "mutable". Everything is an object (except 3 basic types), and all objects are mutable. This means you can use some technology that does not exist in other languages. For example, dynamically add properties to functions.
Copy the codeThe code is as follows:
function displayError(error){
++;
alert(error);
}
= 0;// means that predefined classes and objects can be modified
You can use the prototype mechanism to dynamically add the class instance after it is created, and it is still valid for defined objects. For example:
Copy the codeThe code is as follows:
function Person(name, age) {
= name;
= age;
}
= {
getName: function() {
return ;
},
getAge: function() {
return ;
}
};
//Define two variables first
var miracle = new Person("Miracle", 28);
var mike = new Person("Mike", 32);
// Dynamically add a method
= function() {
return "Hello " + () + "!";
};
//displayGreeting() is only valid for Miracle
= function() {
alert(());
}
Related to object volatility is reflection (also known as "introduction"), which means checking the properties and methods of objects at runtime and using this information to instantiate classes and execute methods, and even without knowing their names during development. With these two major features of objects, you can completely imitate the advanced features of object-oriented languages, but remember that in Javascript any object can be modified at runtime.
5. Javascript has the talent to implement "inheritance". Let me briefly mention it here: Javascript inheritance includes "classical" inheritance and object-based prototype inheritance. I will discuss this topic in detail in the next issue of the article.
Finally, let’s summarize, what are the benefits 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. It helps to reduce coupling between modules, and the code in the project can be divided by module and functional responsibilities.
(2). Easy to communicate. For a large team, it may be possible to highly summarize the functional modules you are responsible for in terms of simple design patterns without having to pay too much attention to the details of the rest of the team.
(3). Improve performance. Utilization mode can reduce the amount of code transmitted to the client while increasing the speed of program operation.
Of course, there are advantages and disadvantages. The disadvantages are:
(1). The complexity is relatively high. The cost of obtaining maintainability is based on the highly refactoring and modular division of the code, which is difficult for some newbies to adapt to.
(2). Some modes reduce performance instead. But this drag depends on your project needs, and may sometimes be trivial and sometimes difficult to accept.
Therefore, it is recommended that everyone learn to understand the application scenarios of design patterns. Using the right scene is the true application of the design patterns. Blindly applying and using the wrong scenario is misuse, and it is better not to use it.