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, with all kinds of incredible uses from the front end to the back end. Programmers use it to complete increasingly large projects.
The complexity of Javascript code has also increased sharply. A single web page contains 10,000 lines of Javascript code, which has long been commonplace. In 2010, an engineer revealed that the code length of Gmail is 443,000 lines!
To write and maintain such complex code, modular strategies must be used. At present, the mainstream approach in the industry is to adopt "object-oriented programming". Therefore, how Javascript implements object-oriented programming has become a hot topic.
The trouble is that Javascipt syntax does not support "class" (class), which makes traditional object-oriented programming methods impossible to use directly. Programmers have done a lot of explorations to study how to simulate "classes" with Javascript. This article summarizes three methods of Javascript defining "classes", discusses the characteristics of each method, and emphasizes the best method in my eyes.
==============================================================
Three ways to define a class in Javascript
In object-oriented programming, a class is a template for an object that defines the properties and methods shared by the same group of objects (also known as "instances".
The Javascript language does not support "classes", but some workarounds can be used to simulate "classes".
1. Constructor method
This is a classic method and a must-teach method in textbooks. It uses a constructor to simulate "class" and uses this keyword to refer to the instance object inside it.
The code copy is as follows:
function Cat() {
this.name = "big hair";
}
When generating an instance, use the new keyword.
The code copy is as follows:
var cat1 = new Cat();
alert(cat1.name); // Big hair
The properties and methods of the class can also be defined on the constructor's prototype object.
The code copy is as follows:
Cat.prototype.makeSound = function(){
alert("meow meow");
}
For a detailed introduction to this method, please see the series of articles I wrote, "Javascript Object-Oriented Programming", I won't talk about it here. Its main disadvantage is that it is relatively complex and uses this and prototype, which is very laborious to write and read.
2. Object.create() method
In order to solve the shortcomings of the "constructor method" and to more conveniently generate objects, the fifth edition of ECMAScript, the international standard of Javascript (the third edition is currently available), proposed a new method Object.create().
Using this method, a "class" is an object, not a function.
The code copy is as follows:
var Cat = {
name: "Big Hair",
makeSound: function(){ alert("Meow Meow Meow"); }
};
Then, use Object.create() directly to generate an instance without using new.
The code copy is as follows:
var cat1 = Object.create(Cat);
alert(cat1.name); // Big hair
cat1.makeSound(); // Meow Meow Meow Meow
Currently, the latest versions of major browsers (including IE9) have deployed this method. If you encounter an old browser, you can use the following code to deploy it yourself.
The code copy 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 attributes and private methods, and data cannot be shared between instance objects, so the simulation of "classes" is not comprehensive enough.
3. Minimalist law
Dutch programmer Gabor de Mooij proposed a new approach that was better than Object.create(), which he called "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, which is probably why it is called "minimalist law".
First of all, it also uses an object to simulate "class". In this class, define a constructor createNew() to generate an instance.
The code copy 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.
The code copy is as follows:
var Cat = {
createNew: function(){
var cat = {};
cat.name = "big hair";
cat.makeSound = function(){ alert("Meow Meow"); };
return cat;
}
};
When using it, call the createNew() method to get the instance object.
The code copy is as follows:
var cat1 = Cat.createNew();
cat1.makeSound(); // Meow Meow Meow Meow
The advantage of this approach is that it is easy to understand, has a clear and elegant structure, and is in line with the traditional "object-oriented programming" construction, so the following features can be easily deployed.
3.2 Inheritance
It is very convenient to implement one class in the next class. Just call the createNew() method of the latter in the createNew() method.
First define an Animal class.
The code copy is as follows:
var Animal = {
createNew: function(){
var animal = {};
animal.sleep = function(){ alert("Sleep in"); };
return animal;
}
};
Then, in Cat's createNew() method, Animal's createNew() method is called.
The code copy is as follows:
var Cat = {
createNew: function(){
var cat = Animal.createNew();
cat.name = "big hair";
cat.makeSound = function(){ alert("Meow Meow"); };
return cat;
}
};
The Cat instance obtained in this way will inherit both the Cat class and the Animal class.
The code copy is as follows:
var cat1 = Cat.createNew();
cat1.sleep(); // Sleep in
3.3 Private attributes and private methods
In the createNew() method, as long as the methods and properties that are not defined on the cat object are private.
The code copy 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 cat's public method makeSound().
The code copy 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 this internal data inside the class object and outside the createNew() method.
The code copy 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, two instance objects are generated:
The code copy is as follows:
var cat1 = Cat.createNew();
var cat2 = Cat.createNew();
cat1.makeSound(); // Meow Meow Meow Meow
At this time, if there is an instance object and the shared data is modified, the other instance object will also be affected.
The code copy is as follows:
cat2.changeSound("Lalala");
cat1.makeSound(); // Lalala
(over)