English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Writing of JavaScript Classes

We know that there is no concept of class in JavaScript. All instance objects of classes inherit properties from the same prototype object, therefore, the prototype object is the core of the class.

A class is an abstraction of an object, and an object is a concrete instance of a class. A class is abstract and does not occupy memory, while an object is concrete and occupies storage space.—百度百科

Early JavaScript requirements were very simple, mostly written as functions, then procedural writing, and later, the concept of object-oriented development was gradually introduced, and then classes were gradually written.

In JavaScript, the essence of writing classes is mostly constructor functions+Prototype. Below, let's discuss several ways to write classes in JavaScript:

Constructor method

/**
* Person class: Defines a person with name attribute and getName method
  */
<script>
  function Person(name) {
    this.name = name;
    this.getName = function(){
      return this.name;
    }
  }
  //We instantiate several objects here
  var p1 = new Person("trigkit4");
  var p2 = new Person("mike");
  console.log(p1 instanceof Person);//true
  console.log(p2 instanceof Person);//true
</script>

As can be seen from the output of the above console, p1and p2It is indeed an instance object of the class Person. The left side of the instanceof operator is the object to be detected, and the right side is the constructor of the defined class. Here, instanceof is used to detect the object p1Whether it belongs to the Person class.

The advantage of this method is that we can construct different object instances based on parameters, but the disadvantage is that each time an instance object is constructed, the getName method is generated, causing memory waste.

We can use an external function to replace class methods, achieving shared methods among all objects. The rewritten class is as follows:

//External function
<script>
  function getName() {
    return this.name;
  }
  function Person(name) {
    this.name = name;
    this.getName = getName;//
  }
</script>

Prototype method

<script>
  function Person(){};
  Person.prototype.name = "trigkit"4";//All class properties are placed on the prototype
  Person.prototype.getName = function() {
    return " I'm " + this.name;
  }
  var p1 = new Person();
  var p2 = new Person();
  console.log(p1.name);//trigkit4
  console.log(p2.getName());//I'm trigkit4
</script>

The disadvantage of the prototype method is that it cannot construct object instances through parameters (generally each object's properties are different), and the advantage is that all object instances share the getName method (compared to the constructor method), without causing memory waste.

Constructor+Prototype method
Take the advantages of the first two:
a. Define class properties (fields) using the constructor.
b. Define class methods using the prototype method.

<script>
  function Person(name) {
    this.name = name;
  }
  //The characteristics of the prototype allow object instances to share the getName method
  Person.prototype.getName = function() {
    return " I'm " + this.name;
  }
</script>

This way, we can both construct objects with different properties and also share methods among object instances without wasting memory.

To make the js code style more compact, we move the prototype method code inside the curly braces of function Person.

<script>
  function Person(name) {
    this.name = name;
    Person.prototype.getName = function() {
      return name;//It is not advisable to use this.name
    }
  }
  var p1 = new Person('trigkit4');
  console.log(p1.getName());//trigkit4
</script>

Here, we need to know several ways to define classes, in addition to the above constructor, including:

Object.create() method
With this method, "class" is an object rather than a function.

 var Person = {
    name : "trigkit"4"
    age : 21,
    run: function() {
      alert("I like running");
    }
  }

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

var p1 = Object.create(Person);
  alert(p1.age);//21
  p1.run();//I like running

This method is simpler than the "constructor method", but it cannot implement private properties and private methods, and instance objects cannot share data, which is not comprehensive enough to simulate the "class".

createNew() method
This method does not need to use this and prototype, the approach is to use an object to simulate a class, and then define a constructor createNew() in the class, and then define the instance object in createNew(), and return this instance object as the return value.

<script>
  var Person = {
    createNew : function () {
      var person = {};
      person.name = "trigkit4";
      person.run = function(){
        alert("I like running");
      };
      return person;
    }
  }
</script>

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

 var p1 = Person.createNew();
  p1.run();//I like running

This writing style is actually very similar to the writing style of object literal, just one is separated by commas, and the other is separated by semicolons.

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo artificial editing, and does not assume relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like