Home > Web Front-end > JS Tutorial > One of the object-oriented Javascript (first introduction to Javascript)_js object-oriented

One of the object-oriented Javascript (first introduction to Javascript)_js object-oriented

WBOY
Release: 2016-05-16 17:56:42
Original
939 people have browsed it

1. The biggest feature of Javascript is its flexibility. As a front-end developer, you can use either a functional programming style or a more complex object-oriented programming style. No matter which style you adopt, you can accomplish some very useful tasks. Therefore, Javascript is a process-oriented language and an object-oriented language, which can imitate the programming patterns and idioms of object-oriented languages. Let's use an example to illustrate: starting and stopping animations.

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

Copy the code The code is as follows:

function startAnimation() {
//Enable animation
}
function stopAnimation() {
//Stop animation
}

This method is simple, but it cannot create animated objects that save state and only operate on internal state. Below we define a class:
Copy code The code is as follows:

var Animation = function() {
//Animation class
};
Animation.prototype.start = function() {
//Enable animation
};
Animation.prototype.stop = function() {
//Stop animation
};
/*Usage as follows*/
var anim = new Animation();
anim.start();
anim.stop() ;

If you want to encapsulate the class definition into a declaration, the code is as follows:
Copy code The code is as follows:

var Animation = function() {
//Animation class
};
Animation.prototype = {
start: function() {
//Enable animation
},
stop: function(){
//Stop animation
}
};

This way the orientation The object's programmer looks more familiar, we can try a more complex way of writing:
Copy the code The code is as follows:

Function.prototype.method = function(name, fn){
this.prototype[name] = fn;
}
var Animation = function() {
//Animation class
};
Animation.method("start", function(){
//Enable animation
});
Animation.method("stop", function( ){
//Stop 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 code The code is as follows:

Function.prototype.method = function(name, fn){
this.prototype[name] = fn;
return this;
}
var Animation = function() {
//Animation class
};
Animation.method("start", function(){
//Enable animation
}).method("stop", function() {
//Stop animation
});

So far, I have seen 5 different programming styles, with different code amounts, coding efficiency and execution performance. You can work in the programming style that best suits your current project.

2. Javascript is a weakly typed language. You don't have to specify a type when declaring a variable, but that doesn't mean there is no type. Javascript contains three basic types: boolean, numeric and string types, as well as object types and function types, and finally empty types and undefined types. Primitive types are passed by value, other types are passed by reference. The type can be changed according to variable assignment, and basic types can be converted to each other. toString() can convert a numerical or Boolean value into a string, parseInt() and parseFloat() can convert a string into a numerical value, and the double "not" operation can convert a string or numerical value into a Boolean value.

3. Javascript functions are "first-class" objects. Functions can be stored in variables, passed as arguments to other functions, passed as return values ​​from other functions, or constructed at runtime. When dealing with functions, it brings great flexibility and strong expressive capabilities, which are the basis for building object-oriented. Anonymous functions can be created through function() {...} (without a function name, it can also be assigned to a variable). The following is an example:
Copy code The code is as follows:

(function(){
var a = 10;
var b = 5;
alert(a * b);//Return 50
})();//The function definition will be executed immediately

The reason why it can be executed immediately is because of the pair of parentheses after the function declaration. But we find that it is not entirely the case that there is nothing in the brackets.
Copy code The 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, except that the variable is not in the function It is declared inside, but passed in directly from the outside. In fact, this anonymous function can also have a return value and assign it to a variable.
Copy code The code is as follows:

var c = (function(a, b){
return a * b;//Return 50
})(10, 5);//Equivalent to the previous
alert(c);//50

Anonymous function The biggest use is to create closures. The so-called closure is a protected variable space generated by embedded functions. Since Javascript has function-level scope, that is, variables defined inside a function cannot be accessed outside the function. The function only runs in the scope in which it is defined, not in the calling scope. In this way, variables can be protected by wrapping them in anonymous functions. For example, you can create a private variable by:
Copy the code 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, b, even if it is executed outside the anonymous function

4. Javascript object is "Variable". Everything is an object (except the 3 basic types), and all objects are mutable. This means you can use some techniques that don't exist in other languages. For example, add attributes dynamically to functions.
Copy code The code is as follows:

function displayError(error){
displayError.numTimesExecuted ;
alert(error);
}
displayError.numTimesExecuted = 0;//It means that predefined classes and objects can be modified

You can use the prototype mechanism to When an instance of a class is created and then added dynamically, it is still valid for the defined object. For example:
Copy code 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;
}
};
//First define two variables
var miracle = new Person("Miracle", 28 );
var mike = new Person("Mike", 32);
//Dynamicly add a method
Person.prototype.getGreeting = function() {
return "Hello " this.getName () "!";
};
//displayGreeting() is only valid for Miracle
miracle.displayGreeting = function() {
alert(this.getGreeting());
}

Related to the mutability of objects is reflection (also called "introspection"), which checks the properties and methods of objects at runtime and uses this information to instantiate classes and execute methods, even during development No need to know their names. With the help of these two characteristics 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 talent to implement "inheritance". Here is a brief mention: Javascript inheritance includes "class" inheritance and object-based prototype inheritance. I will discuss this topic in detail in the next article.

Finally, to summarize, what are the benefits of using object-oriented and design pattern ideas to deal with a seemingly procedural language like Javascript? I have summarized the following points for your reference:

(1). Maintainability. It helps to reduce the coupling between modules, and the code in the project can be divided according to modules and functional responsibilities.

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

(3). Improve performance. Exploiting patterns can reduce the amount of code sent to the client and increase the speed of program execution.

Of course, there are pros and cons. The disadvantages are:

(1). The complexity is relatively high. The cost of obtaining maintainability is a high degree of code reconstruction and modular division, which is difficult for some novices to adapt to at once.

(2). Some modes actually reduce performance. But depending on your project needs, this drag may be trivial or unacceptable.

Therefore, it is recommended that everyone learn to understand the application scenarios of design patterns. Using the right scenarios is the true application of design patterns. Blind application or use in the wrong scenario is misuse, and it is better not to use it.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template