Three ways to define JavaScript classes (Class)

Source: Internet
Author: User

Three ways to define JavaScript classes (Class)

Almost 20 years ago, when JavaScript was born, it was just a simple web scripting language. If you forget to fill in the user name, it jumps out a warning.

Today, it becomes almost omnipotent, from the front-end to the back-end, with a variety of unthinkable uses. Programmers use it to accomplish larger and larger projects.

The complexity of JavaScript code also rises linearly. A single page contains 10000 lines of JavaScript code, which is commonplace. 2010, an engineer revealed that Gmail's code length is 443000 lines!

To write and maintain such complex code, you must use a modular strategy. At present, the mainstream practice of the industry is to adopt "object-oriented Programming". Thus, how JavaScript implements object-oriented programming becomes a hot topic.

The trouble is that the JAVASCIPT syntax does not support "class", resulting in a traditional object-oriented programming approach that cannot be used directly. Programmers have done a lot of exploring how to emulate "classes" with JavaScript. This paper summarizes three methods of JavaScript definition "Class", discusses the characteristics of each method, and emphatically introduces the best method in my eyes.

==============================================

Three ways to define JavaScript classes (Class)

Nanyi

In object-oriented programming, a class is a template for objects (object) that defines properties and methods common to the same set of objects (also known as "instances").

The JavaScript language does not support "classes," but you can use some workarounds to simulate "classes."

First, the method of constructing function

This is the classic method, but also the textbook must teach method. It simulates a "class" with a constructor, within which it uses the This keyword to refer to an instance object.

function Cat () {

THIS.name = "Mao";

}

When generating an instance, use the New keyword.

var cat1 = new Cat ();

alert (cat1.name); Da Mao

The properties and methods of the prototype class can also be defined on top of the constructor's object.

Cat.prototype.makeSound = function () {

Alert ("Meow Meow");

}

For a detailed introduction to this method, please see my series of articles, "Javascript Object-oriented programming", which is not much to say here. Its main disadvantage is that it is more complicated, and it is very laborious to write and read the prototype.

Second, object.create () Law

In order to solve the disadvantage of "constructor method", it is more convenient to generate objects, JavaScript International standard ECMAScript Fifth edition (currently in the third edition), proposed a new method Object.create ().

In this way, "class" is an object, not a function.

var Cat = {

Name: "Da Mao",

Makesound:function () {alert ("Meow Meow");}

};

Then, generate the instance directly with Object.create (), without the need for new.

var cat1 = object.create (Cat);

alert (cat1.name); Da Mao

Cat1.makesound (); Meow Meow

Currently, the latest versions of major browsers (including IE9) have deployed this method. If you encounter an old-fashioned browser, you can deploy it yourself with the following code.

if (! Object.create) {

Object.create = function (o) {

function F () {}

F.prototype = O;

return new F ();

};

}

This method is simpler than "constructor method", but it cannot implement private properties and private methods, nor can data be shared between instance objects, and the simulation of "class" is not comprehensive enough.

Iii. Minimalist Law

The Dutch programmer, Gabor de Mooij, proposed a new approach that was better than object.create (), which he called the "minimalist approach" (minimalist approach). This is also my recommended method.

3.1 Package

This method does not use this and prototype, and the code is very simple to deploy, which is probably why it is called "minimalism."

First, it also simulates "class" with an object. Inside this class, define a constructor createnew (), which is used to generate the instance.

var Cat = {

Createnew:function () {

Some code here

}

};

Then, in CreateNew (), define an instance object that takes the instance object as the return value.

var Cat = {

Createnew:function () {

var cat = {};

Cat.name = "Mao";

Cat.makesound = function () {alert ("Meow Meow");};

return cat;

}

};

When used, the instance object can be obtained by invoking the CreateNew () method.

var cat1 = Cat.createnew ();

Cat1.makesound (); Meow Meow

The benefit of this approach is that it is easy to understand, the structure is clear and elegant, and conforms to the traditional "object-oriented programming" constructs, so the following features can be easily deployed.

3.2 Inheritance

It is convenient to have one class inherit another class. As long as in the former CreateNew () method, call the latter's CreateNew () method.

Define a animal class first.

var Animal = {

Createnew:function () {

var animal = {};

Animal.sleep = function () {alert ("Sleeping in");};

return animal;

}

};

Then, in the Cat's CreateNew () method, call the animal's CreateNew () method.

var Cat = {

Createnew:function () {

      var cat = Animal.createnew ();

Cat.name = "Mao";

Cat.makesound = function () {alert ("Meow Meow");};

return cat;

}

};

The cat instances that are obtained will inherit both the cat class and the animal class.

var cat1 = Cat.createnew ();

Cat1.sleep (); Sleep

3.3 Private properties and private methods

In the CreateNew () method, the methods and properties that are not defined on the Cat object are private.

var Cat = {

Createnew:function () {

var cat = {};

      var sound = "Meow meow meow";

      Cat.makesound = function () {alert (sound);};

return cat;

}

};

The internal variable sound of the above example cannot be read externally, only through cat's public Method MakeSound ().

var cat1 = Cat.createnew ();

  alert (cat1.sound); Undefined

3.4 Data sharing

Sometimes, we need all the instance objects to be able to read and write the same internal data. This time, as long as the internal data, encapsulated in the class object inside, CreateNew () method outside.

var Cat = {

    Sound: "Meow meow Meow",

Createnew:function () {

var cat = {};

      Cat.makesound = function () {alert (cat.sound);};

      Cat.changesound = function (x) {cat.sound = x;};

return cat;

}

};

Then, build two instance objects:

var cat1 = Cat.createnew ();

var cat2 = Cat.createnew ();

Cat1.makesound (); Meow Meow

At this point, if there is an instance object that modifies the shared data, the other instance object is also affected.

  Cat2.changesound ("La la La");

Cat1.makesound (); La La la

Three ways to define JavaScript classes (Class)

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.