One of the object-oriented JavaScript (beginner JavaScript) _js Object oriented

Source: Internet
Author: User
Tags anonymous function definition inheritance numeric numeric value valid
1. The biggest feature of JavaScript is its flexibility. As a front-end developer, either functional programming style or a more complex object-oriented programming style can be used. No matter which style you use, you can accomplish some very useful tasks. Therefore, JavaScript is a process-oriented language, but also an object-oriented language, which can imitate the object-oriented language programming patterns and idiomatic methods. Let's use an example to illustrate: Start and stop animations.

If you are accustomed to functional programming style, the code will be as follows:
Copy Code code as follows:

function Startanimation () {
Enable animation
}
function StopAnimation () {
Stop animation
}

This approach is simple, but it is not possible to create an animated object that saves state and operates only on internal states. Here we define a class:
Copy Code code as follows:

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

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

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

This makes the object-oriented programmer look more familiar, and we can try something a little more complicated:
Copy Code code 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 extend a method for the function class to add a new method. Name represents the function name, and FN represents the concrete implementation of the function. On the basis of this notation, we can let the function support chained calls:
Copy Code code 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
});

Now you've seen 5 different programming styles, with varying amounts of code, coding efficiencies, and execution performance. You can choose the programming style that works best for your current project.

2. JavaScript is a weakly typed language. Declaring a variable does not necessarily specify a type, but does not mean that it does not have a type. JavaScript contains three basic types: Boolean, numeric, and string, in addition to object types and function types, and finally to empty and undefined types. The base type is passed by value, and other types are passed by reference. You can change the type based on the variable assignment, and the base types can be converted to each other. ToString () converts a numeric or Boolean value to a string, parseint () and parsefloat () can convert a string to a numeric value, and a double "non" operation converts a string or numeric value to a Boolean value.

3. JavaScript functions are "first-class" objects. Functions can be stored in variables and passed as arguments to other functions, either as return values from other functions or at run time. In the function of dealing with, bring great flexibility and strong ability to express, these are building object-oriented basis. You can use the function () {...} Create an anonymous function (without a function name, or assign to a variable). Here is an example to illustrate:
Copy Code code as follows:

(function () {
var a = 10;
var B = 5;
Alert (A * b);//Return 50
}) ();//function definition executes immediately

It is executed immediately because of a pair of parentheses after the function declaration. But we found that there was nothing in the parentheses and it was not entirely so.
Copy Code code 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 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 variable.
Copy Code code as follows:

var c = (function (A, b) {
Return a * b;//50
}) (10, 5);//is equivalent to the preceding
alert (c);//50

The most useful use of anonymous functions is to create closures. The so-called closure, is a protected variable space, generated by the inline function. Because JavaScript has a function-level scope, a variable defined within a function cannot be accessed outside of a function, and the function runs only in the scope in which it is defined, not in the scope of the call. This allows the variable package to be protected in an anonymous function. For example, you can create a private variable in the following ways:
Copy Code code as follows:

var C;
(function () {
var a = 10;
var B = 5;
c = function () {
Return a * b;//50
}
})();
C ();//c can access a,b even if it is executed outside the anonymous function

4. JavaScript objects are "variable". Everything is an object (except for 3 basic types), and all objects are variable. This means you can use some technology that doesn't exist in other languages. For example, add properties dynamically to a function.
Copy Code code as follows:

function DisplayError (Error) {
displayerror.numtimesexecuted++;
alert (error);
}
displayerror.numtimesexecuted = 0;//means that predefined classes and objects can be modified

You can use the prototype mechanism to add dynamically after an instance of a class is created, which is still valid for the defined object. For example:
Copy Code code 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);
Dynamically add a method
Person.prototype.getGreeting = function () {
Return "Hello" + this.getname () + "!";
};
Displaygreeting () is valid only for miracle
miracle.displaygreeting = function () {
Alert (this.getgreeting ());
}

Related to the variability of an object is reflection (also known as "introspection"), that is, checking the properties and methods of an object at run time, and using that information to instantiate classes and execute methods, even when developing without having to know their names. With these two features of the object, you can completely emulate the advanced features of an object-oriented language, but remember that any object in JavaScript can be modified at run time.

5. JavaScript has the gift of "inheritance". Here's a quick mention: JavaScript inheritance includes "Class" Inheritance and object-based prototype inheritance, which I'll cover in more detail in the next installment.

Finally, what are the benefits of using object-oriented and design-mode ideas to deal with the seemingly procedural language of JavaScript? I have summed up 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 into modules and functional responsibilities.

(2). Easy to communicate. For a large team, it is possible to generalize the functional modules that you are responsible for by using a term that is very simple in design mode, without having to focus too much on the details of other members of the team.

(3). Improve performance. Using patterns can reduce the amount of code delivered to the client and increase the speed at which the program runs.

Of course, the advantages have disadvantages. The disadvantage is:

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

(2). Partial mode decreases performance. But this drag depends on your project needs, and may sometimes be trivial and sometimes difficult to accept.

Therefore, we suggest that you learn to understand the design pattern of the application scene, with the scene is the design pattern of the real meaning of the application. Blind application and use of the wrong scene is misused, as well as not.
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.