_javascript techniques for writing JavaScript classes

Source: Internet
Author: User

We know that in JS, there is no concept of the class. All instance objects of a class inherit properties from the same prototype object, so 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. Classes are abstract, do not occupy memory, and objects are specific and occupy storage space. ——— Baidu Encyclopedia

Early JavaScript requirements are simple, basically written function, and then the process-oriented writing, and then slowly introduced object-oriented development ideas, and then slowly written into the class.

In JS, the essence of the written class is basically a constructor + prototype. Next, discuss some of the JS class writing:

Structural function method

/**
* Person class: Defines a human, has the name attribute and the GetName method
  */
<script> function Persons
  (name) {
    THIS.name = Name;
    This.getname = function () {return
      this.name;
    }
  }

  Here we instantiate several objects
  
  var p1 = new Person ("TRIGKIT4");
  var p2 = new Person ("Mike");

  Console.log (P1 instanceof person),//true
  console.log (p2 instanceof person);//true
</script>

The output from the above console indicates that P1 and P2 are indeed instance objects of the class person. The left side of the instanceof operator is the object for the instrumented class, and the right is the constructor that defines the class. Here, instanceof is used to detect whether the object P1 belongs to the person class.

The advantage of this method is that we can construct different object instances according to the parameters, the disadvantage is that every time the instance object is constructed, the GetName method is generated, resulting in the waste of memory.

We can use an external function instead of a class method to achieve the same method that each object shares. The rewritten classes are as follows:

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

  function person (name) {
    this.name = name;
    This.getname = getname;//
  }
</script>

Prototype mode

<script>
  Function Person () {};
  Person.prototype.name = "TRIGKIT4";//class attributes 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 approach is that it is not possible to construct object instances through parameters (typically, the properties of each object are not the same), and the advantage is that all object instances share GetName methods (as opposed to constructors) and do not cause memory waste.

Constructor + Prototype method
Take advantage of the previous two:
A, use constructors to define class properties (fields).
B, the method of defining the class in a prototype way.

<script>
  function Person (name) {
    this.name = name;
  }

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

In this way, we can either construct objects of different attributes or let object instances share methods without causing a waste of memory.

To make the JS code more compact, we let the prototype method code move to the curly braces of the function person.

<script>
  function Person (name) {
    this.name = name;
    Person.prototype.getName = function () {return
      name;//not suitable for this.name
    }
  }

  var p1 = new Person (' Trigkit4 ');
  Console.log (P1.getname ());//TRIGKIT4
</script>

Here we need to know several methods of defining classes, in addition to the constructors above, as well:

Object.create () method
in this way, "class" is an object, not a function.

 var person = {
    name: ' Trigkit4 ',
    age:21,
    run:function () {
      alert ("I like Running");
    }
  

Then, you generate the instance directly with Object.create () without using new.

var P1 = object.create (person);
  alert (p1.age);//21
  P1.run ();//i like running

This method is simpler than "constructor method", but it can't realize private property and private method, the instance object can not share data, and the simulation of "class" is not comprehensive enough.

CreateNew () method
This method does not require this and prototype, by simulating a class with an object, and then defining a constructor in the class CreateNew (), and then defining the instance object in CreateNew () to take the 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 used, the CreateNew () method is invoked, and the instance object can be obtained.

 var p1 = person.createnew ();
  P1.run ();//i like running

This type of writing is very similar to the object literal, except that one is comma-delimited and one is semicolon-delimited.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.