JS-class- inheritance and development model

 

Methods inherited detailed study js

1 ES5 implementation of (standard prior to 2015)

js a complex object is achieved by way of the prototype chain, Function Method prototype prototype stored in the subclass __proto__in the constructor must be used constructor function newkey

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, can not pass parameters to the parent class 2, class attribute value shared by all subclasses

Constructor 1.2

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: The method can not be inherited, call the corresponding constructor, not inherited copy of the prototype.

1.3 Combined

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: sub-class attribute information of the two parent class, flawed

1.4 parasitic combined

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);
}

<!-- 关键点:单独创建constructor,并继承父类然后赋给子类原型 -->
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 formula

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

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

or

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 that exist in the object, the parent object acts as an object prototype, the prototype instance attributes are shared by all instances can not be reused, is now added attribute, the function package is not

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: to create objects -> Enhance -> return objects
  • Disadvantages: can not be reused

2 ES6 implementation of (ES2015)

2.1 declare the class

  • Define a class, you need the class keyword, declare as follows:
// 类的名称按照原则和编程习惯首字符应该大写!
class Error {
  // constructor中添加初始化类实例的时候,需要传入的变量
  constructor(type, date, source) {
      this.type = type;
      this.date = date;
      this.source = source;
  }
}
  • Expressions class declaration
// 声明匿名的类
let Rect = class {
    constructor (height) {
        this.height = height;
    }
};
let r = new Rect(100);
 
 // 声明具名的类
let RectAngle = class Rect {
    constructor (width) {
        this.width = width;
    }

    getClassName () {
        return Rect.name;
    }
}

  • Two or more types of declarative statements will not advance, we must first declare.
  • And a statement error, the class name will be written to memory, it is that the wrong class name has been taken.

Whether constructor is required?

A class must have a constructor method! If the declaration is not displayed a constructor will silently add a constructor  a class equivalent to a function, there will be a constructor, this constructor returns can modify the default return and have supre method inherited from the parent class inside

2.2 class body and wherein

  • Statements and expressions strict mode the main class of default are performed in strict mode, the trend is for ES6. Constructors, static methods, prototyping, getter, setter are performed in strict mode.

  • Special class constructor method used to create and initialize an object. Each class can have only one constructor has multiple constructors will report a syntax error. Constructors can use the superconstructor keyword call the parent class.

  • Getter and Setter Methods

class Rect {
    constructor () {
        //  ...声明类的属性
    }

    // 使用 get set 关键字,对某个属性进行存值和取值时,执行相应操作
    get prop () {
        return '获取prop';
    }

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

}

var rectIns = new Rect();
rectIns.prop;  // 获取prop
rectIns.prop = '新的prop'; // setter: 新的prop

  • Class of property class属性包括3种:静态属性,实例属性,原型属性。

  • Property and assign access

类的属性不能通过super作为对象的时候访问,实例属性可以通过super对象的时候给子类添加属性,然后还是用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();

2.3 class static method

Static characteristics of

静态方法的创建和引用方式,直接作用在函数或者类上
实例方法和属性在constructor或者原型上
静态方法不能被类的实例使用
实例方法和属性也不能被静态方法使用
静态方法和属性可以被子类继承
静态方法可调用静态属性

Declare static methods and static properties are as follows:

class Animal {
    // 定义静态方法
    static getsomething () {
        console.log('exe static function: ', this.feature);
    }
}
// 不能在class内部定义static变量
Animal.feature = 'staticAttrs';
Animal.getsomething(); // exe static function: staticAttrs

Static methods and properties of the class, method, and attribute instance with the same name may be because two different spaces, hanging in a static method Function, the example method hanging Objecton. Visit each other less, you will be prompted undefined.

2.4 class inherits

  • Class inheritance must use the super keyword and extends keyword For chestnuts
class Animal {
    constructor(height, weight) {
        this.height = height;
        this.weight = weight;
    }
}

class Dog extends Animal {
    constructor(height, weight, color) {
        // super声明在前
        super(height, weight);
        this.color = color;
    }
    // 这个方法默认放在父类的原型上
    generateAnimal () {
        return this.color;
    }
}

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

labuladuo instanceof Animal;
labuladuo instanceof Dog;

Where, super () constructor key role similar inheritance A.prototype.constructor.call (this) (or the original inheritance js) super () to generate your own constructor with the parent class constructor and then after restatement this. color = color, have their own constructor

super.x = '子类super赋值等同于给this赋值';

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

Like the prototype chain to inherit, if A.prototype = new B () prototype will be extended until new B () covers the usage is very similar to the need to declare, but the essence of difference.

  • After super super super keyword as a subclass object (), it can be considered super itself is an object, the prototype parent class points
super.height === Animal.prototype.height  // true

superAnimal represent but does not mean the parent class prototype. Therefore, in subclasses by super.generateAnimal () method of the embodiment can call the parent class prototype.

  • super Examples of property can not be accessed or subclasses of the parent class constructor.

  • super No gesture can not use; super There are two default attributes, as a function and as an object, but it must be implicitly specified, otherwise there will be an error.

  • If the static super static method, a static method will inherit 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

2.5 class prototype and __proto__

  • 1 prototype chain) subclass inherits on js __proto__point to the parent classes, inheritance represents 2) constructor subclass prototypeof the __proto__point to the parent class prototypeinherits For example, the representation
class A {}
class B extends A {}
B.__proto__ === A // true
b.prototype.__proto__ === A.prototype  // true

2.6 succession native constructor

Constructor native comprising: 9 kinds of

Boolean
String
Number
Array
RegExp
Date
Error
Object
Function

Error object created extensions

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"

Extended tool magazine (custom tool magazine), such as a DOM node object as a parameter, the method of operating a node as an extension of the tool magazine a node inherit parent class.

Guess you like

Origin www.cnblogs.com/the-last/p/11204549.html