JS-class-inheritance and development model

Posted by AaZmaN on Wed, 17 Jul 2019 18:51:20 +0200

Learn more about how js inherits

1 ES5 implementation (pre-2015 standards)

The reuse of js objects is accomplished by prototype chains. Function methods are stored in prototype prototype in u proto_ of subclasses. Constructors in constructor s must use the new keyword

1.1 Prototype Chain

function Parent () {
    this.name = 'haha';
    this.car = ['area', 'auto'];
}
Parent.prototype.getinfo = function () {
    return `name:  ${this.name} + age: ${this.car}`;
}

function Child () {
    this.name  = 'heihei';
}
Child.prototype = new Parent();
var child = new Child();
child.getinfo(); // name: heihei car: area auto;

var childOther = new Parent();
childOther.car.push('bmw');
child.getinfo(); // name: heihei car: area auto bmw;
  • Disadvantages: 1. Parameters cannot be passed to the parent class, 2. Attribute values of classes are shared by all subclasses

1.2 Constructor

function Parent (name) {
    this.name = name;
    this.car = ['area','auto'];
}

function Child (name) {
    Parent.call(this, name);
}
var child1 = new Child('haha');
var child2 = new Child('heihei');

child1.push('bmw');
child2.car;  //  area auto

  • Disadvantages: Method cannot be inherited, call corresponds to constructor, and copy of prototype cannot be inherited.

1.3 Combination

function Parent (name) {
    this.name = name;
    this.car = ['area', 'auto'];
}
Parent.prototype.getinfo = function () {
    return `name: ${this.name} + car: ${this.car}`;
}

function Child (name) {
    Parent.call(this, name);
}
Child.prototype = new Parent();
var child1 = new Child('haha');
child1.getinfo();  // name: haha + car: area auto
var child2 = new Child('heihei');
child2.car.push('bmw');
child1.getinfo();  // name: haha + car: area auto 
child2.getinfo();  // name: haha + car: area auto bmw 

  • Disadvantages: A subclass has two pieces of attribute information from its parent, which is flawed

1.4 Parasitic Combination

function Parent (name) {
    this.name = name;
    this.car = ['area', 'auto'];
}
Parent.prototype.getinfo = function () {
    return `name: ${this.name} + car: ${this.car}`;
}

function Child (name) {
    Parent.call(this, name);
}

<!-- Key Point: Create Individually constructor,And inherit the parent class and assign it to the child class prototype -->
var proto = Object.create(Parent.prototype);
proto.constructor = Child;
Child.prototype = proto;

var child1 = new Child('haha');
child1.getinfo(); // name: haha + car: area auto
var child2 = new Child('heihei');
child2.getinfo(); // name: heihei + car; area autp
child2.car.push('bmw');
child1.getinfo(); // name: haha + car: area auto
  • Disadvantages: basically perfect

1.5 prototype

function Parent() {
    this.name = 'haha';
    this.car = ['area', 'auto'];
}

var child = Object.create(new Parent());
child.attr1 = 'new job';

perhaps

function Parent () {
    this.name = 'heihei';
    this.car = ['auto'];
}
function deget (obj) {
    var F = function () {};
    F.prototype = obj;
    return new F();
}
var child = deget(new Parent());
child.attr1 = 'new job';
  • Disadvantages: Derived objects on existing objects, parent objects acting as prototype objects, prototype instance attributes can not be reused by all instances, attributes are present, functions are not encapsulated

1.6 Parasitic

function beget(obj) {
    var F = function(){};
    F.prototype = obj;
    return new F();
}
function Super() {
    this.val = 1;
    this.arr = [1];
}

function getSubObject (obj) {
    var clone = beget(obj);
    clone.attr1 = 1;
    clone.attr2 = 2;

    return clone;
}
var sub = getSubObject(new Super());
console.log(sub.val);
console.log(sub.arr);
console.log(sub.attr1);

  • Principle: Create Object-->Enhancement-->Return Object
  • Disadvantage: Can not be reused

How 2 ES6 is implemented (ES2015)

Declaration of class 2.1

  • The definition of a class requires a class keyword, which is declared as follows:
// Class names should be capitalized according to principles and programming habits!
class Error {
  // When adding an instance of an initialization class in the constructor, you need to pass in a variable
  constructor(type, date, source) {
      this.type = type;
      this.date = date;
      this.source = source;
  }
}
  • Expression declaration of class
// Declare anonymous classes
let Rect = class {
    constructor (height) {
        this.height = height;
    }
};
let r = new Rect(100);
 
 // Declare named classes
let RectAngle = class Rect {
    constructor (width) {
        this.width = width;
    }

    getClassName () {
        return Rect.name;
    }
}

  • Neither of these classes will be declared in advance, so be sure to declare them first.
  • And a declaration error, the name of the class will be written to memory, that is, the wrong class name has been occupied.

Is the constructor required?

A class must have a constructor method!If you do not declare a constructor as shown, you will silently add a constructor, a class is equivalent to a function, there must be a constructor, and the constructor will return this to modify the default return, with the supre method inheriting the parent class internally

Class 2.2 Bodies and Characteristics

  • Declarations and expression bodies of strict schema classes are executed in strict mode by default, which is also a trend in ES6.Constructors, static methods, prototype methods, getter s, and setter s are all executed in strict mode.

  • A special method of a constructor class used to create and initialize an object.Each class can only have one constructor, and more than one will report a syntax error.Constructors can use the super keyword to call the parent class's constructor.

  • Getter and Setter methods

class Rect {
    constructor () {
        //  ... Declare the properties of a class
    }

    // Use the get set keyword to store and evaluate an attribute
    get prop () {
        return 'Obtain prop';
    }

    set prop (value) {
        console.log('setter: ', value);
    }

}

var rectIns = new Rect();
rectIns.prop;  // Get prop
rectIns.prop = 'New prop'; // setter: new prop

  • class attributes include three types: static attributes, instance attributes, and prototype attributes.

  • Assignment and access to attributes

Class properties cannot be accessed when super is an object. Instance properties can be accessed by adding properties to subclasses when super is an object, and then by using this!

class Animal {
    constructor () {
        this.name = 'history'
    }
    myDog () {
        console.log(333);
    }
}
class Dog extends Animal {
    constructor () {
        super();
        this.childName = 'now';

    }
    setSuper () {
        super.newName = '666';
    }
    getSuper () {
        console.log(this.newName);     //666
        console.log(this.childName);   //now
        console.log(this.name);        //history
        console.log(super.name);       //undefined
        console.log(super.childName);  //undefined
        console.log(super.newName);    //undefined
    }
}

var dog = new Dog();
dog.getSuper();

Static methods of class 2.3

Characteristics of Static Mode

Static methods are created and referenced directly on functions or classes
Instance methods and properties on a constructor or prototype
Static methods cannot be used by instances of classes
Instance methods and properties cannot be used by static methods either
Static methods and properties can be inherited by subclasses
Static methods can invoke static properties

Static methods and static properties are declared as follows:

class Animal {
    // Define static methods
    static getsomething () {
        console.log('exe static function: ', this.feature);
    }
}
// static variable cannot be defined inside class
Animal.feature = 'staticAttrs';
Animal.getsomething(); // exe static function: staticAttrs

Class static methods and properties, which can have the same name as instance methods and properties because there are two different spaces, static methods on Function and instance methods on Object.No mutual access, will prompt undefined.

Inheritance of class 2.4

  • Class inheritance must use the super and extends keywords to raise a chestnut
class Animal {
    constructor(height, weight) {
        this.height = height;
        this.weight = weight;
    }
}

class Dog extends Animal {
    constructor(height, weight, color) {
        // super declaration before
        super(height, weight);
        this.color = color;
    }
    // This method defaults to the parent class's prototype
    generateAnimal () {
        return this.color;
    }
}

let labuladuo = new Dog(1, 30, 'brown');

labuladuo instanceof Animal;
labuladuo instanceof Dog;

Where the super() keyword acts like the constructor's inheritance A.prototype.constructor.call(this) (or js'original inheritance) super() first generates its own constructor with the parent constructor and then declares this.color = color to have its own constructor

super.x = 'Subclass super Assignment is equivalent to giving this assignment';

class B extends A {
  constructor() {
    super();
    this.x = 2;
    super.x = 3;
    console.log(super.x); // undefined
    console.log(this.x); // 3
  }
}

Like prototype chain inheritance, if extended prototype is overridden by new B() before A.prototype = new B(), the usage is very similar and needs to be declared first, but the substance is different.

  • After using super() as an object in a subclass, you can think of super as an object, pointing to the prototype of the parent class
super.height === Animal.prototype.height  // true

Super represents but is not equal to the prototype of the parent Animal class.So the super.generateAnimal() method on the parent prototype can be called in the subclass.

  • Sup cannot access instance properties of a subclass or parent constructor.

  • Super cannot be used without posture; super has two default attributes, as a function and as an object, but must be specified implicitly or an error will occur.

  • If super is used in a static method, it inherits the static method of the parent class as follows:

class Animal {
    static myDog (dog) {
        console.log('static function: ', dog);
    }
    myDog (dog) {
        console.log('instance function: ', dog);
    }
}
class Dog extends Animal {
    static myDog (dog) {
        super.myDog(dog)
    }
}
Dog.myDog('labuladuo');  // static function: labuladuo

prototype and u proto_u of class 2.5

  • About prototype chain of js inheritance 1) Subclass u proto_ points to parent class, representing inheritance of constructor 2) Subclass u proto_ points to prototype of parent class, representing inheritance of method as an example
class A {}
class B extends A {}
B.__proto__ === A // true
b.prototype.__proto__ === A.prototype  // true

2.6 Inheritance of native constructors

Native constructors include nine

Boolean
String
Number
Array
RegExp
Date
Error
Object
Function

Create Extensions for Error Objects

class ExtendError extends Error {
    constructor (message) {
        super();
        this.name = this.constructor.name;
        this.message = message;
        this.stack = (new Error()).stack;
    }
}   

var myError = new ExtendError('12');
myError.message; // '12'
myError instanceof Error;  // true 
myError.stack;  
// "Error
//     at new ExtendError (<anonymous>:6:23)
//     at <anonymous>:10:15"

Extend the Tool Library (Custom Tool Library), such as using DOM node objects as parameters and node operation methods as inherited parent classes for node tool library extension.

Topics: PHP Attribute Programming