Javascript object oriented encapsulation and inheritance

  • 2020-03-30 04:25:29
  • OfStack

Tidy up the encapsulation and inheritance in js object orientation.

1. The encapsulation
Js encapsulation has many ways to implement, here is a list of several commonly used.

1.1 the original schema generates the object
Write our member directly to the object and return it as a function. Cons: it's hard to see an instance of a pattern coming out.

Code:


       function Stu(name, score) {
            return {
                name: name,
                score: score
            }
        }
        var stu1 = Stu(" Zhang SAN ", 80);
        var stu2 = Stu(" Li si ", 90);
        console.log(stu1.name); //Zhang SAN < br / >

1.2 generate construction-mode objects

Js provides us with a pattern of using constructors to generate objects. A "constructor" is just a normal function, but it USES this variable internally. When an instance is generated using the new keyword pair constructor, this variable is bound to the instance object.

Direct code:


      function Stu(name, score) {
            this.name = name,
            this.score = score
        }
        var stu1 = new Stu(" Zhang SAN ", 80);
        var stu2 = new Stu(" Li si ", 90);
        console.log(stu1.name + "/" + stu2.score); //Zhang SAN   90 < br / >         console.log((stu1.constructor == Stu) + "/" + (stu2.constructor == Stu)); // true  true
        console.log((stu1 instanceof Stu) + "/" + (stu2 instanceof Stu)); // true  true

It is not difficult to see that js constructor generates objects just like C# generates objects with class, both using templates to define object members and instantiating them with the new keyword.

Generate the same Stu object with C# code


Class Stu
{
  public string name;
  public double score;                   
}

Ok, so here's the basic object. So now we need a method that is common to all objects, and we only want this method to be created once. What about (not being created repeatedly with the object new)? You all know that in C# we can use static members. So what do we do in js?

1.3 the Prototype model

In js, each constructor has a prototype property, and all the properties and methods of this object are inherited by the constructor's instance. So adding a member to prototype is like declaring a static member in C#.

Code:


      function Stu(name, score) {
            this.name = name,
            this.score = score
        }
        Stu.prototype.type=' students ';
        Stu.prototype.log = function (s) {
            console.log(s);
        }
        var stu1 = new Stu(" Zhang SAN ", 80);
        var stu2 = new Stu(" Li si ", 90);
        console.log(stu1.type + "/" + stu2.type); //Students students
        stu1.log('hello');  // hello
        console.log(stu1.log == stu2.log);  // true

So with that out of the way, let's take a look at how inheritance is implemented in js.

2. The inheritance

2.1 constructor binding

Directly call the call or apply method in the child function, binding the constructor of the parent object to the child object.
 


   function Stu(name, score) {
            Grade.apply(this, arguments);
            //Grade.call(this, arguments);
            this.name = name,
            this.score = score
        }
        function Grade() {
            this.code = " Junior high school ";
            this.ask = function () {
                console.log(" Hello, everyone ");
            }
        }
        var stu1 = new Stu(" Zhang SAN ", 80);
        var stu2 = new Stu(" Li si ", 90);
        console.log(stu1.code); //Junior high school < br / >         stu1.ask(); //Hello everyone

Apply here does two things, giving the first parameter, this, to the Grade constructor (caller), and then executing the code in Grade. This is equivalent to executing the members of Grade defined with this in Stu again.

2.2 inheritance through prototype
Look at the code

Code:


    function Stu(name, score) {
            this.name = name,
            this.score = score
        }
        function Grade() {
            this.code = " Junior high school ";
        }
        Stu.prototype = new Grade();
        Stu.prototype.constructor = Stu; //To prevent the inheritance chain from getting out of order, manually reset the declaration
        var stu1 = new Stu(" Zhang SAN ", 80);
        var stu2 = new Stu(" Li si ", 90);
        console.log(Stu.prototype.constructor); //Its own constructor
        console.log(stu1.code); //Junior high school < br / >

As mentioned earlier, prototype is equivalent to a static member in C#, so we will make all the members of the parent class our own static members to implement inheritance.

There is one drawback to prototype inheritance: all inherited members are static, so how do you inherit object members?

2.3 copy inheritance

Copy all the properties and methods of the parent object into the child object to implement inheritance.

Code:


    function Stu(name, score) {
            this.name = name,
            this.score = score
        }
        function Grade() {}
        Grade.prototype.code = " Junior high school ";
    }
        //Function encapsulation
        function extend(C, P) {
            var p = P.prototype;
            var c = C.prototype;
            for (var i in p) {
                c[i] = p[i];
            }
        }
        extend(Stu, Grade);
        var stu1 = new Stu(" Zhang SAN ", 80);
        var stu2 = new Stu(" Li si ", 90);
        stu1.code=' High school ';
        console.log(stu1.code); //High school < br / >         console.log(stu2.code); //Junior high school < br / >         console.log(Stu.prototype.constructor);
        console.log(Grade.prototype.constructor)

      Js object-oriented arrangement is written here, this thing is not the same, when the use of their own needs to change.   There is a saying that is very good, the right is the best.

This article only focuses on encapsulation and inheritance, and we will do some other articles later to give you a deeper understanding of javascript object-oriented programming. Of course, all of them are personal understandings. If there is anything missing, please contact me.


Related articles: