How to implement classes in JavaScript explore _javascript techniques

Source: Internet
Author: User
Tags getmessage
There are many ways to create objects in JavaScript, so creating objects is a very flexible way to use them. So which is the most appropriate way to create an object? Construct pattern, prototype mode or object intent mode (objects literal)?

But what exactly is the pattern?

Before we begin, let's start with a clear introduction to JavaScript basics.

Is there any way you can implement object-oriented programming in JavaScript?

The answer is possible, JavaScript is the object that can be created! This object can contain data and methods to manipulate the data, and can even contain other objects. It does not have a class but has a constructor; it does not have a class inheritance mechanism, but it can implement inheritance through a prototype (prototype).

Now it looks like we've learned the components that are necessary to create objects in JavaScript and implement object-based programming.

We all know that JavaScript has private variables. A variable defined by the "var" keyword can only be accessed in the body of the function, not outside the function. So what happens if we don't define variables by using the "var" keyword? We are not going to delve into this issue now, possibly through "this", and I will be talking about it in detail at another time.

Now go back to the previous question. Which is the most appropriate way to create an object?
Let's experiment with the knowledge we already know by creating the object of person.
Copy Code code 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 = ' Eli ';
Person.lastname = ' Flowers '
Person.changemessage (' welcome ');
var message = Person.getmessage (); Welcome Eli Flowers
alert (message);

This is the object Intent mode (literal pattern). This is very close to how we often create objects. If you do not need to care about the private/packaging members, and you know that you will not create an instance of this object. Well, this way will be good for you. A public member can do all the private stuff, right? However, this is not a class, but an object that cannot be created and cannot be inherited.

Let's try the other side:
Copy Code code 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 = ' Eli ';
Person.lastname = ' Flowers '
Person.changemessage (' welcome ');
var message = Person.getmessage (); Welcome Eli Flowers
alert (message);

This is an instance of a construction pattern (constructor patterns). So, is this a class or an object? Should be two kinds of it. We can use it as an object person when the request is made. It's just a function, after all. However, it can be implemented by using the "new" keyword to create a new instance feature.

when using this approach, we need to keep the following points in mind:

1. Whenever this function is invoked, it has a special variable called "This" and can be used globally. The global scope depends on the scope of the function itself.

2. Whenever you create an instance of this function through the "new" keyword, the "This" variable points to the function itself, and the "new" operation will affect the execution of the code in the function body. This is also the construction model.

3. Any variable attached to the "this" variable becomes a public property and any variable defined through the "var" keyword will be owned by a private property.

4. A function attached to "this" is called a privileged function that can access all the private variables and the functions and variables that are appended to "this".

5. Private functions can be accessed to other private variables and private functions.

6. Private functions cannot be directly accessed by attaching to "this" variables and functions. We can implement this by creating a private variable "_that" and assigning it as "this".

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

8. A variable: not through the "var" keyword, nor is it attached to the "this" variable to achieve global scope. For example, the scope of a custom function. Need to understand the scope and cluster knowledge once again.

This has already achieved most of the requirements we want, but sometimes the two entry variables "this" and "that" can easily create confusion. Especially for those who have always insisted on pure private, it is easier to confuse.

Let's try it a little bit more.
Copy Code code 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 (' Eli ');
Person1.setlastname (' Flowers ');
Person1.setmessage (' welcome ');
var message = Person1.getmessage (); Welcome Eli Flowers
alert (message);

This is a display mode (revealing pattern). Thank you very much Christian Heilmann. The way to use this pattern is to use the requested "getters" and "setters" as attributes. Many of us have found such a figure in traditional Java programming and clearly know that it is not complicated to implement it. This is similar to the case where a class inherits from an interface.

Most of this pattern is well implemented, with only one small problem. Every time an instance of a class is created. This newly created object obtains a copy of the variables and functions. Now, the copy variable is fine, and we want the data for each object to belong to the object itself, so what about the member function? They're just manipulating data. So why do we need to copy them?

This is the advantage of the prototype model (PROTOTYPE). In all instances, everything is created into a prototype and can be shared with each other. All we need to do is create a common function based on the prototype.
Copy Code code 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 () {}; would 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 to new person (); person; New Person ();
};


var person1 = new Person ();
Person1.setfirstname (' Eli ');
Person1.setlastname (' Flowers ');
Person1. Changemessage (' welcome ');
var message = Person1.getfullname (); Welcome Asdsad Flowers
alert (message);

One of the problems with prototyping patterns is that it doesn't have access to private variables and private functions, and that's why we introduce closures and always organize the code that exists in a class so that it doesn't get messy in the global context. 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 binding of the stereotype. For some of us, this is only a matter of efficiency. One way to handle this problem is to bind this prototype only if you expect the common function to be unavailable.

This will allow the bound prototype operation to be executed only when the first instance is created, and all other instances will only be checked after that. Unfortunately, this still does not solve the problem we mentioned in the above example, because we only have to recreate the function to create a closure to achieve the effect of this class. In this case, at least we have reduced the use of some of the memory.

Wait, there is another problem is that private functions cannot directly access prototype functions.

Why do you have to need private functions and private variables? I know you must be trying to implement the encapsulation of the class, to make sure that the attributes or internal data in the class are not suddenly modified or modified by other internal programs, or any other operation ...

You should remember that you are not able to compile JavaScript code into binary, and in this case, you are annoyed to some extent, so that the code is always available. So, if anyone wants to mess with the code, whether you're really private or not, whether you're giving the code to other members of the team or selling it, they can scramble the code. Privatization could be a little bit of a help.

Another technique used by other programmers is to use the Convention name, using the underscore "_" to prefix everything you want to make private, to specify that it be private.
Copy Code code 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 = ' Eli ';
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 designer of the code, so you will know how to manage and know how to do the best. Depending on your needs, you can use any design pattern or combination of multiple design patterns.

Whatever design pattern you decide to adopt, always remember to do as little as possible, do not implement closures in a global scope, minimize memory leaks, optimize your code, and organize your code. So, try to learn more about scopes, closures, and behavior of "this".

Finally, I wish the programming happy!

post-translation sense

Always use JavaScript, the impression of it is always a direct copy of it can be used. Recently used ExtJS, its class framework is very useful. This article also understands the various ways in which classes are implemented in JavaScript, and the implementation of private members in a class is discussed 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.