Functional vs object-oriented JavaScript programming

Source: Internet
Author: User
Tags jquery library

Click here for the original article

The flexible JS language can easily complete the opposite two programming modes-functional programming and object-oriented programming.

JS native supports processing functions as variables. You can assign a function to a variable and pass it to another variable. Abstract: we can think of a JS function as a special variable, but its form is "function ".

JS native also provides objects. In JS, objects can be considered as flat attribute values and methods. They look like a data dictionary, not as you see in other objects such as Java, C ++, and C. In classical object-oriented programming, class representation can generate an instance template through the new operator. However, in JS, no object can be generated as a blue object. In JS, the blueprint of an object is more like a data dictionary. Therefore, in JS, you can create an object and then store data in the object. Of course, JS objects also provide a certain degree of object-oriented features, such as encapsulation and inheritance.

JS development is getting hotter and hotter. What are the advantages and disadvantages of the two models? JS supports both modes, but you have to figure out the answer to the question. It supports both of them, but it is not particularly appropriate. Oop JS frameworks and function-Type JS both exist.

Introduction to functional programming

In function programming, each code segment is built on the "function", which is different from the traditional OOP built on the "class. A function is only an operation for displaying input. A function only receives some input and returns some output. Others are hidden.

In function programming, you call other functions in a function to complete program input and output. This usually does not have the layer that can process input, storage data, and a series of status updates. A function is similar to a numeric value and can be passed as a parameter to other functions.

JavaScript and functional programming

One thing that needs to be clarified is that JS is not really a functional programming language like F #, although it has some features of functional programming patterns. With these features, you can also use js to do a good job. So far, jquery is the most widely used model.

Anonymous functions are the essence of functional programming. An anonymous function is another form of Lambda computing. It can adapt to popular encoding styles.

123
function (x,y){     return x + y;}

The only difference between a common function and an anonymous function is its name. In the context of a function, when you only need the return value of the function to be used as a parameter, you do not have to give it a function name. Let's take a look at the following example:

123456789101112131415161718
// A function var calctotal = function (x, y) {return x + y ;}; // increase the tax rate var addtaxes = function (X) {return x * 1.2;}; // final calculation function var calctotalplustaxes = function (fncalctotal, fnaddtaxes, x, y) {return fnaddtaxes (fncalctotal (X, y) ;}; // execute var result = calctotalplustaxes (calctotal, addtaxes, 40, 60); alert (result );

You can also use anonymous functions instead of passing them to the final formula through an intermediate variable.

123
alert(     (function(x){return x * 1.2})(100););

Using anonymous functions as a variable makes it easy to combine data and features. This also gives you the opportunity to experiment with some other design principles. When a module at the higher level (whether an object or a function) requires the return value provided by a module at the lower level, it can directly pass the module at the lower level as a parameter. In many cases, this will improve the readability of function parameters and make the code more elegant. Of course, it will also make you more comfortable in dealing with complicated things.

Jquery and functional programming

Jquery attracts great attention in functional programming. The entire jquery library is based on jquery objects or $. $ Is an encapsulation of DOM elements. DOM elements can also be passed through the $ () expression. In addition, jquery supports chained operations. After each function is run, the same jquery object is returned.

Jquery is very efficient, because you can maximize the power of functional programming in a web programming environment that operates DOM elements. You may be a fan of jquery and think this function operation is awesome. However, this is not a reason to completely use this programming mode everywhere. The following jquery source code is used as an example:

12345678
jQuery.fn = jQuery.prototype = {    init: function( selector, context ) { ... },       size: function() { return this.length; },       each: function( callback, args ) {        return jQuery.each( this, callback, args );  },       ready: function( fn ) { ... }       :}

As you can see, the jquery object has its own prototype and some methods, such as size and each. More interestingly, when you write jquery plug-ins, you just extend the prototype method by adding a function. So far, all efficient JS programming is the result of a mixture of two modes. Of course, the functional model in jquery is more obvious.

Objects in Javascript

Objects in object-oriented programming are obviously different from those in JavaScript. In object-oriented languages, classes are the blueprint of the objects you want to use. In JavaScript, the source of the object you use is a data dictionary or function. When you create an object in JS, you have an empty data dictionary that you can fill in any data.

As mentioned before, you can create custom objects or inherit from existing objects through some methods. This is only valid in Js.

When you need to add Intermediate conversions to access the real object-oriented language, there are two methods in javascript: Closure and prototype.

Before talking about the two methods, let's talk about the object types and their usage in Js.

You can use the new keyword to create an empty object. Then you can add the object to the desired content:

123456789101112131415161718
var person = new Object();person.Name = "Dino";person.LastName = "Esposito";person.BirthDate = new Date(1979,10,17)person.getAge = function() {  var today = new Date();  var thisDay = today.getDate();  var thisMonth = today.getMonth();  var thisYear = today.getFullYear();  var age = thisYear-this.BirthDate.getFullYear()-1;  if (thisMonth > this.BirthDate.getMonth())      age = age +1;  else  if (thisMonth == this.BirthDate.getMonth() &&      thisDay >= this.BirthDate.getDate())      age = age +1;  return age;}

We now have an object named person, but there is no person object. In JS, all original sound objects have a read-only prototype attribute. You can use this attribute to provide some functions. When using the new keyword, these functions can share these methods with the new object. There are two ways to implement Object-Oriented Programming in JS.

Implement object-oriented through closures

Closures are a basic concept in programming languages. In JS, a closure is a function of variables and methods with the same context. The following example uses a closure to simulate a person class:

1234567891011121314151617181920
var Person = function(name, lastname, birthdate){   this.Name = name;   this.LastName = lastname;   this.BirthDate = birthdate;    this.getAge = function() {      var today = new Date();      var thisDay = today.getDate();      var thisMonth = today.getMonth();      var thisYear = today.getFullYear();      var age = thisYear-this.BirthDate.getFullYear()-1;      if (thisMonth > this.BirthDate.getMonth())          age = age +1;      else         if (thisMonth == this.BirthDate.getMonth() &&             thisDay >= this.BirthDate.getDate())             age = age +1;      return age;   }}

We can see that the closure is the constructor of the parent class. In the closure mode, the constructor contains the declaration of class members, and these members are encapsulated. In addition, the members are all instance-based, so the memory will be consumed. How to use it:

12
var p = new Person('Rock','ux',new Date());alert(p.name + 'is' + p.getAge());

The closure mode is completely encapsulated.

Object-oriented Method of prototype mode

Using prototype objects in JS, you can define the structure of a class. The following example shows how to avoid using closures to override the person class.

12345678910111213141516171819202122232425262728
// Constructor var person = function (name, lastname, birthdate) {This. initialize (name, lastname, birthdate);} // member person. prototype. initialize (name, lastname, birthdate) {This. name = Name; this. lastname = lastname; this. birthdate = birthdate;} person. prototype. getage = function () {var today = new date (); var ThisDay = today. getdate (); var thismonth = today. getmonth (); var Thisyear = today. getfullyear (); var age = thisYear-this.BirthDate.getFullYear ()-1; if (thismonth> This. birthdate. getmonth () age = age + 1; else if (thismonth = This. birthdate. getmonth () & ThisDay> = This. birthdate. getdate () age = age + 1; return age ;}

In the prototype mode, the constructor and the members have a clear structure, but the constructor is required. There is no private member here. The VaR keyword can make it only valid in the closure. You can define setter/getter to operate on the attributes you need, but these attributes can be directly accessed and modified outside the class. You can use some special operations (such as adding a prefix) to define private variables. It's just a way.

The prototype can be easily inherited:

12345
Developer = function Developer(name, lastname, birthdate){   this.initialize(name, lastname, birthdate);}Developer.prototype = new Person();

Note that you must use the this keyword to access the relevant member methods in the prototype.

Closure or prototype?

In prototype mode, all members are shared. Therefore, the memory overhead is smaller. Apart from syntax differences, classes defined through prototype are closer to object-oriented languages in the classic sense.

The choice of closure or prototype should also be based on the performance and browser compatibility. The loading speed of the prototype mode is good, and the performance in Firefox is also good. (The closure mode is faster to load under ie .) The prototype provides good support for smart sensing, so that you can get good tool support in some IDES (such as. In prototype mode, you do not have to create an instance to view the type information. In closure mode, you cannot. Finally, during debugging, the prototype mode can easily access private members. The closure mode takes several steps below.

For example, Microsoft's Ajax library uses the prototype mode (the closure mode is never considered ).

Conclusion

Javascript is not a pure functional or object-oriented language. However, you need to be prepared to learn from both languages.

Today, JavaScript is essential for compiling client web pages and mobile applications. In addition, the current script writing is not like the time when the language was used. Now we often use Js for client form verification and other programs. To make the development process more stable, we also need some JS libraries. Jquery is the best example.

As jquery shines, the function type becomes more important in Javascript language than in object-oriented language. In the end, you choose what you want. You do not have to choose a development mode as you believe. It is very common to use both of them in development.

As mentioned above, if I am a front-end developer, I may use jquery and then use some anonymous functions without worrying about any custom objects. If I want to write a JS library by myself, I will definitely choose object-oriented development, closure mode or prototype mode.

Click to view Original Text

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.