Home  >  Article  >  Web Front-end  >  Detailed explanation of three methods of defining classes in Javascript_javascript skills

Detailed explanation of three methods of defining classes in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:501256browse

Nearly 20 years ago, when Javascript was born, it was just a simple web scripting language. If you forget to fill in your username, it will pop up a warning.

Nowadays, it has become almost omnipotent, from front-end to back-end, with all kinds of incredible uses. Programmers use it to complete increasingly larger projects.

The complexity of Javascript code has also skyrocketed. It has long been common for a single web page to contain 10,000 lines of Javascript code. In 2010, an engineer revealed that Gmail’s code length was 443,000 lines!

Writing and maintaining such complex code requires a modular strategy. At present, the mainstream approach in the industry is to adopt "object-oriented programming". Therefore, how to implement object-oriented programming in Javascript has become a hot topic.
The trouble is that Javascript syntax does not support "class" (class), making traditional object-oriented programming methods unable to be used directly. Programmers have done a lot of research on how to simulate "classes" in Javascript. This article summarizes three ways to define "classes" in Javascript, discusses the characteristics of each method, and focuses on the best method in my eyes.

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

Three ways to define classes in Javascript

In object-oriented programming, a class is a template for an object, which defines the properties and methods common to the same group of objects (also called "instances").

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

1. Constructor method

This is a classic method and a method that must be taught in textbooks. It uses a constructor to simulate a "class" and uses the this keyword internally to refer to the instance object.

Copy code The code is as follows:

function Cat() {
  this.name = "大毛";
}

When generating an instance, use the new keyword.
Copy code The code is as follows:

var cat1 = new Cat();
alert(cat1.name); // Da Mao

The attributes and methods of a class can also be defined on the prototype object of the constructor.

Copy code The code is as follows:

Cat.prototype.makeSound = function(){
alert("meow meow meow");
}

For a detailed introduction to this method, please read the series of articles I wrote "Javascript Object-Oriented Programming", so I won’t go into details here. Its main disadvantage is that it is relatively complicated, uses this and prototype, and is very laborious to write and read.

2. Object.create() method

In order to solve the shortcomings of the "constructor method" and generate objects more conveniently, the fifth edition of ECMAScript, the international standard for Javascript (the third edition is currently popular), proposes a new method Object.create().
With this method, a "class" is an object, not a function.

Copy code The code is as follows:

var Cat = {
  Name: "大毛",
  makeSound: function(){ alert("Meow Meow Meow"); }
};

Then, directly use Object.create() to generate an instance without using new.

Copy code The code is as follows:

​var cat1 = Object.create(Cat);
alert(cat1.name); // Da Mao
cat1.makeSound(); // Meow Meow Meow

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

Copy code The code is as follows:

​if (!Object.create) {
  Object.create = function (o) {
    function F() {}
   F.prototype = o;
   return new F();
  };
}

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

3. Minimalism Method

Dutch programmer Gabor de Mooij proposed a new method that is better than Object.create(), which he called the "minimalist approach". This is also the method I recommend.

3.1 Packaging

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

First of all, it also uses an object to simulate a "class". In this class, define a constructor createNew() to generate instances.

Copy code The code is as follows:

var Cat = {
​​createNew: function(){
    // some code here
  }
};

Then, in createNew(), define an instance object and use this instance object as the return value.

Copy code The code is as follows:

var Cat = {
​​createNew: function(){
   var cat = {};
   cat.name = "大毛";
   cat.makeSound = function(){ alert("Meow Meow Meow"); };
   return cat;
  }
};

When using it, call the createNew() method to get the instance object.

Copy code The code is as follows:

​var cat1 = Cat.createNew();
cat1.makeSound(); // Meow Meow Meow

The advantage of this method is that it is easy to understand, has a clear and elegant structure, and conforms to the traditional "object-oriented programming" construct, so the following features can be easily deployed.

3.2 Inheritance

Let one class inherit another class, which is very convenient to implement. Just call the latter's createNew() method in the former's createNew() method.

First define an Animal class.

Copy code The code is as follows:

var Animal = {
​​createNew: function(){
   var animal = {};
animal.sleep = function(){ alert("Sleep in"); };
   return animal;
  }
};

Then, in Cat’s createNew() method, call Animal’s createNew() method.

Copy code The code is as follows:

var Cat = {
​​createNew: function(){
   var cat = Animal.createNew();
   cat.name = "大毛";
   cat.makeSound = function(){ alert("Meow Meow Meow"); };
   return cat;
  }
};

The Cat instance obtained in this way will inherit both the Cat class and the Animal class.
Copy code The code is as follows:

​var cat1 = Cat.createNew();
cat1.sleep(); // Sleep in

3.3 Private properties and private methods

In the createNew() method, all methods and properties that are not defined on the cat object are private.

Copy code The code is as follows:

var Cat = {
​​createNew: function(){
   var cat = {};
   var sound = "meow meow meow";
   cat.makeSound = function(){ alert(sound); };
   return cat;
  }
};

The internal variable sound in the above example cannot be read externally and can only be read through the public method makeSound() of cat.
Copy code The code is as follows:

​var cat1 = Cat.createNew();
alert(cat1.sound); // undefined

3.4 Data Sharing

Sometimes, we need all instance objects to be able to read and write the same internal data. At this time, just encapsulate the internal data inside the class object and outside the createNew() method.

Copy code The code is as follows:

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, generate two instance objects:

Copy code The code is as follows:

​var cat1 = Cat.createNew();
var cat2 = Cat.createNew();
cat1.makeSound(); // Meow Meow Meow

At this time, if one instance object modifies the shared data, the other instance object will also be affected.
Copy code The code is as follows:

cat2.changeSound("La La La");
cat1.makeSound(); // La La La

(End)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn