Methods for implementing classes in JavaScript

Source: Internet
Author: User

There are many methods to create objects in JavaScript implementation class, so the method to create objects is flexible. 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 does not have a class but has a constructor. It does not have a 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. [Javascript] 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. changeMessag E ('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 do not know that the instance will be created 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: [javascript] var Person = function () {this. firstName = 'john'; this. lastName = 'cody '; var fullName = ''; this. message = ''; var _ that = this; var createFullName = function () {fullName = _ that. firstName + ''+ _ that. lastName;} this. changeMessage = function (msg) {this. message = msg;} this. getMessage = function () {createFullName (); return this. message + ''+ fullName;} var Person1 = new Person (); person1.firstName = 'lil'; person1.lastName = 'flowers' person1.changeMessage ('Welcome '); var message = person1.getMessage (); // welcome Eli Flowers alert (message); this is a Constructor Pattern instance ). 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 generation in the function body to be executed. 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. [Javascript] 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 ge TMessage = 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 display mode (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. [Javascript] 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 mescript E = person1.getFullName (); // welcome asdsad Flowers alert (message); a problem in 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 are not 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. [Javascript] (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'm not saying 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! Javascript is often used after translation, 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.