How to Implement classes in JavaScript _ javascript skills

Source: Internet
Author: User
There are many ways to create objects in javascript, so the method for creating objects is very flexible. which method is the most appropriate? The following describes how to create an object in javascript in many ways. Which method is the most appropriate method for object creation? What about the construction mode, prototype mode, or Object literal mode?

But what are these patterns?

Before proceeding, let's give a clear introduction to the basic knowledge about javascript.

Is it possible to implement Object-Oriented Programming in javascript?

The answer is yes. javascript can create objects! This type of object can contain data, methods that can operate on data, and even other objects. It has no class but constructor; it does not have class inheritance mechanism, but can be inherited through prototype.

Now it seems that we have learned the necessary components for creating objects in javascript and implementing object-based programming.

We all know that javascript has private variables. A variable defined by the "var" keyword can only be accessed in the function body, but not outside the function. So what if we don't use the "var" keyword to define the variable? We will not discuss this issue in depth now. It may be accessed through "this". I will discuss this issue in detail at another time.

Now let's go back to the previous issue. Which method is the most appropriate object creation method?
Let's use the known knowledge to test it by creating the Person object.

The Code is as follows:


Var Person = {
FirstName: 'john ',
LastName: 'cody ',
FullName :'',
Message :'',

CreateFullName: function (){
FullName = this. firstName + ''+ this. lastName;
},

ChangeMessage: function (msg ){
This. message = msg;
},

GetMessage: function (){
This. createFullName ();
Return this. message + ''+ fullName;
}
}

Person. firstName = 'lil ';
Person. lastName = 'flowers'
Person. changeMessage ('Welcome ');
Var message = Person. getMessage (); // welcome Eli Flowers
Alert (message );


This is the original object pattern ). This is very close to the way we often create objects. If you do not need to care about private/encapsulated members, and you know that you do not want to create an instance for this object. Then, this method will be very suitable for you. Public Members can do all private members, right? However, this is not a class, but an object. It cannot be created and inherited.

Let's try other aspects:

The Code is as follows:


Var Person = {
FirstName: 'john ',
LastName: 'cody ',
FullName :'',
Message :'',

CreateFullName: function (){
FullName = this. firstName + ''+ this. lastName;
},

ChangeMessage: function (msg ){
This. message = msg;
},

GetMessage: function (){
This. createFullName ();
Return this. message + ''+ fullName;
}
}

Person. firstName = 'lil ';
Person. lastName = 'flowers'
Person. changeMessage ('Welcome ');
Var message = Person. getMessage (); // welcome Eli Flowers
Alert (message );


This is a Constructor Pattern ). So, is this a class or an object? Either of them is correct. We can use it as the object Person in a request. After all, it is just a function. However, it can use the "new" keyword to create a new instance.

When using this method, we need to always remember the following points:

1. No matter when this function is called, it has a special variable called "this" and can be used globally. The global scope depends on the scope of the function.

2. whenever an instance of the function is created using the "new" keyword, the "this" variable points to the function itself, and the "new" operation will affect the code execution in the function body. This is also the construction mode.

3. Any variable appended to the "this" variable will become a public property and any variable defined by the "var" keyword will be a private property.

4. A function attached to "this" is called a privileged function. It can access all private variables and functions and variables attached to "this.

5. Private functions can access other private variables and private functions.

6. Private functions cannot directly access the variables and functions attached to "this. We can create a private variable "_ that" and assign it to "this.

7. Any private variables and functions are available for other private functions and other functions attached to "this. This is entirely possible in the scope of javascript.

8. A variable: it does not use the "var" keyword or be appended to the "this" variable to obtain the global scope of action. For example, the scope of a custom function. You need to understand the scope and cluster again.

This has implemented most of the requirements we want. However, sometimes the entry variables "this" and "that" are confusing. It is especially confusing for those who have always insisted on being purely private.

Let's try it again.

The Code is as follows:


Var Person = function (){

// Private
Var firstName = 'john ';
Var lastName = 'cody ';
Var fullName = '';
Var message = '';


Var createFullName = function (){
FullName = firstName + ''+ lastName;
}

// Public setters
Var setMessage = function (msg ){
Message = msg;
}

Var setFirstName = function (fName ){
FirstName = fName;
}

Var setLastName = function (lName ){
LastName = lName;
}

Var getMessage = function (){
CreateFullName ();
Return message + ''+ fullName;
}

// Functions exposed public
Return {
SetFirstName: setFirstName,
SetLastName: setLastName,
SetMessage: setMessage,
GetMessage: getMessage
};

};

Var person1 = new Person ();
Person1.setFirstName ('lil ');
Person1.setLastName ('flowers ');
Person1.setMessage ('Welcome ');
Var message = person1.getMessage (); // welcome Eli Flowers
Alert (message );


This is a Revealing Pattern ). Thank you very much for Christian Heilmann. In this mode, the requested "getters" and "setters" are used as attributes. Many of us find this in traditional Java programming and obviously know that implementing it is not complicated. This is also similar to the case where the class inherits from an interface.

This mode is well implemented in most aspects, and there is only one small problem. Each time a class instance is created. The newly created object obtains a copy of the variables and functions. Now, there is no problem with copying variables. We hope that the data of each object belongs to the object itself. What about member functions? They only operate on data. So why do we need to copy them?

This is the advantage of Prototype. In all instances, everything is created as a prototype and can be shared with each other. All we need to do is create a common function based on the prototype.

The Code is as follows:


Var Person = function (){

// Private
Var welcomeMessage = 'Welcome ';
Var fullName = '';
Var firstName = '';
Var lastName = "";
Var createFullName = function (){
Person. prototype. setFirstName ('asdsad ');
FullName = firstName + ''+ lastName;
};

// Constructor
Var Person = function () {}; // will be created evrytime

// Public
Person. prototype = {
GetFullName: function (){
CreateFullName ();
Return welcomeMessage + ''+ fullName;
},
SetFirstName: function (fName ){
FirstName = fName;
},
SetLastName: function (lName ){
LastName = lName;
},
ChangeMessage: function (mesg ){
WelcomeMessage = mesg;
}
}

Return new Person (); // Person; // new Person ();
};


Var person1 = new Person ();
Person1.setFirstName ('lil ');
Person1.setLastName ('flowers ');
Person1.ChangeMessage ('Welcome ');
Var message = person1.getFullName (); // welcome asdsad Flowers
Alert (message );


A problem with the prototype mode is that it cannot access private variables and private functions, we will introduce the closure and the code that always organizes in the creation class so that it will not become messy globally. All are within the scope of the Person class.

Another problem is that every time an instance is created, all the code is executed, including the prototype binding. For some of us, this is just a matter of efficiency. One way to handle this problem is to bind the prototype only when the expected common function is unavailable.

In this way, the binding prototype operation will only be executed when the first instance is created, and after that, all other instances will only perform the check operation. Unfortunately, this still cannot solve the problem we mentioned in the above example, because we only need to re-create the function to generate a closure to achieve the effect of this class. In this way, at least part of the memory usage is reduced.

Another problem is that private functions cannot directly access the prototype functions.

Why do you need private functions and private variables? I know that you must want to implement the encapsulation of the class, and want to ensure that the attributes or internal data in the class will not be suddenly modified or modified by other internal programs, or any other operations ......

You should remember that you cannot compile javascript code into binary. In this case, you are very annoyed to some extent, so that the code is always available. Therefore, if anyone wants to disrupt the code, no matter whether you are truly private or not private, no matter whether you give the code to other members of the team or sell it, they can disrupt the code. It may be helpful to achieve privatization.

Another technique used by other programmers is to use conventions to name things that you want to set to private by prefixing them with underscores.

The Code is as follows:


(Function (){
Var Person = function (){
This. _ fullName = '';
This. welcomeMessage = '';
This. firstName = '';
This. lastName = "";
_ That = this;

This. _ createFullName = function (){
This. ChangeMessage ('namaste ');
This. _ fullName = this. firstName + ''+ this. lastName;
};
}

// Shared Functions for Code optimization
Person. prototype = {
Constructor: Person,
GetFullName: function (){
This. _ createFullName ();
Return this. welcomeMessage + ''+ this. _ fullName;
},
ChangeMessage: function (mesg ){
This. welcomeMessage = mesg;
}
}

This. Person = Person;
})();

Var person1 = new Person ();
Person1.firstName = 'lil ';
Person1.lastName = 'flowers ';
Person1.ChangeMessage ('Welcome ');
Var message = person1.getFullName (); // Namaste Eli Flowers
Alert (message );


I am not saying that you should not consider "private" or similar knowledge. You are the code designer, so you will know how to manage and how to do it is the best. Based on your needs, you can use any design mode or multiple design modes.

No matter which design mode you choose, always remember to do as few things as possible, do not implement closures within the scope of global effect, minimize Memory leakage, optimize code, and organize code. Therefore, try to learn more about the scope, closure, and "this" behavior.

Finally, I wish you a pleasant programming!

Post-Translation

Javascript is often used, and the impression of it has always been directly copied and can be used. Recently, extjs is used, and its class framework is very useful. This article also understands various methods of implementing classes in javascript, and discusses the implementation of Private Members in the class at the end of the article.
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.