Home  >  Article  >  Web Front-end  >  A detailed introduction to the inheritance methods and pros and cons of js constructors (full code)

A detailed introduction to the inheritance methods and pros and cons of js constructors (full code)

php是最好的语言
php是最好的语言Original
2018-07-26 18:19:511518browse

This article mainly introduces the inheritance of constructors (inheritance of classes), and also includes the introduction of ES5 and ES6. Due to limited abilities, there will inevitably be unreasonable or wrong places in the article. I hope you can criticize and correct me~

js constructor

Prototype

First of all, let’s briefly introduce the instance properties/methods and prototype properties/methods in order to better understand the following

function Persion(name){
    this.name = name;                                       // 属性
    this.setName = function(nameName){                      // 实例方法
        this.name = newName;
    }
}
Persion.prototype.sex = 'man';                              // 向 Persion 原型中追加属性(原型方法)

var persion = new Persion('张三');                          // 此时我们实例化一个persion对象,看一下name和sex有什么区别

View persistence on the console and print it as follows:
A detailed introduction to the inheritance methods and pros and cons of js constructors (full code)The attributes originally added through prototype will appear in the prototype chain of the instance object,
Each object will have a built-inproto Object, when an attribute cannot be found in the current object, it will be searched in its prototype chain (i.e. prototype chain)

Let’s look at the following example
Note: In the constructor, there are generally few reference attributes in the form of arrays. In most cases, they are: basic attribute methods.

function Animal(n) {                                       // 声明一个构造函数
    this.name = n;                                         // 实例属性
    this.arr = [];                                         // 实例属性(引用类型)
    this.say = function(){                                 // 实例方法
        return 'hello world';
    }
}
Animal.prototype.sing = function() {                       // 追加原型方法  
    return '吹呀吹呀,我的骄傲放纵~~';
}
Animal.prototype.pArr = [];                                // 追加原型属性(引用类型)

Next let’s take a look at the difference between instance properties/methods and prototype properties/methods
The purpose of the prototype object is to store shared methods and properties for each instance object. It is just a Just ordinary objects. And all instances share the same prototype object, so unlike instance methods or properties, there is only one copy of the prototype object. There are many instances, and instance properties and methods are independent.

var cat = new Animal('cat');                               // 实例化cat对象
var dog = new Animal('dog');                               // 实例化狗子对象

cat.say === dog.say                                        // false 不同的实例拥有不同的实例属性/方法
cat.sing === dog.sing                                      // true 不同的实例共享相同的原型属性/方法

cat.arr.push('zz');                                        // 向cat实例对象的arr中追加元素;(私有)
cat.pArr.push('xx');                                       // 向cat原型对象的pArr中追加元素;(共享)
console.log(dog.arr);                                      // 打印出 [],因为cat只改变了其私有的arr
console.log(dog.pArr);                                     // 打印出 ['xx'], 因为cat改变了与狗子(dog)共享的pArr

Of course, if the prototype attribute is a basic data type, it will not be shared
In the constructor: for the privacy of attributes (instance basic attributes), and methods (instance reference attributes) reuse and share. We advocate:
1. Encapsulate properties in constructors
2. Define methods on prototype objects

ES5 inheritance method

First, we define a Animal parent class

function Animal(n) {                              
    this.name = n;                                          // 实例属性
    this.arr = [];                                          // 实例属性(引用类型)
    this.say = function(){                                  // 实例方法
        return 'hello world';
    }
}
Animal.prototype.sing = function() {                        // 追加原型方法  
    return '吹呀吹呀,我的骄傲放纵~~';
}
Animal.prototype.pArr = [];                                 // 追加原型属性(引用类型)

1. Prototype chain inheritance

function Cat(n) {
    this.cName = n;
}
Cat.prototype = new Animal();                               // 父类的实例作为子类的原型对象

var tom = new Cat('tom');                                   // 此时Tom拥有Cat和Animal的所有实例和原型方法/属性,实现了继承
var black = new Cat('black');

tom.arr.push('Im tom');
console.log(black.arr);                                     // 打印出 ['Im tom'], 结果其方法变成了共享的,而不是每个实例所私有的,这是因为父类的实例方法/属性变成了子类的原型方法/属性了;

Advantages: The child object realizes the inheritance of the instance methods/properties and prototype methods/properties of the parent object;
Disadvantages: Subclass instances share the reference data type attributes of the parent class constructor.

2. Borrowing the constructor

function Cat(n) {
    this.cName = n;                     
    Animal.call(this, this.cName);                           // 核心,把父类的实例方法属性指向子类
}

var tom = new Cat('tom');                                    // 此时Tom拥有Cat和Animal的所有实例和原型方法/属性,实现了继承
var black = new Cat('black');

tom.arr.push('Im tom');
console.log(black.arr);                                      // 打印出 [], 其方法和属性是每个子类实例所私有的;
tom.sing();                                                  // undefind 无法继承父类的原型属性及方法;

Advantages:
1. Implement the instance method/attribute of the parent object by the child object Inheritance, the parent class instance methods and attributes inherited by each subclass instance are private;
2. When creating a subclass instance, you can pass parameters to the parent class constructor;
Disadvantages: Subclass instances cannot inherit the construction attributes and methods of the parent class;

3. Combined inheritance

function Cat(n) {
this.cName = n;                     
    Animal.call(this, this.cName);                          // 核心,把父类的实例方法属性指向子类
}
Cat.prototype = new Parent()                                // 核心, 父类的实例作为子类的原型对象
Cat.prototype.constructor = Cat;                            // 修复子类Cat的构造器指向,防止原型链的混乱

tom.arr.push('Im tom');
console.log(black.arr);                                     // 打印出 [], 其方法和属性是每个子类实例所私有的;
tom.sing();                                                 // 打印出 '吹呀吹呀,我的骄傲放纵~~'; 子类继承了父类的原型方法及属性

Advantages:
1. When creating a subclass instance, you can pass parameters to the parent class constructor;
2. The instance method of the parent class is defined on the prototype object of the parent class, allowing method reuse. ;
3. Do not share the constructor and attributes of the parent class;
Disadvantages: The constructor of the parent class is called twice

4. Parasitic combination inheritance

function Cat(n) {
this.cName = n;                     
    Animal.call(this, this.cName);                          // 核心,把父类的实例方法属性指向子类
}
Cat.prototype = Parent.prototype;                           // 核心, 将父类原型赋值给子类原型(子类原型和父类原型,实质上是同一个)
Cat.prototype.constructor = Cat;                            // 修复子类Cat的构造器指向,防止原型链的混乱

tom.arr.push('Im tom');
console.log(black.arr);                                     // 打印出 [], 其方法和属性是每个子类实例所私有的;
tom.sing();                                                 // 打印出 '吹呀吹呀,我的骄傲放纵~~'; 子类继承了父类的原型方法及属性
tom.pArr.push('publish');                                   // 修改继承于父类原型属性值 pArr;
console.log(black.pArr);                                    // 打印出 ['publish'], 父类的原型属性/方法 依旧是共享的,
// 至此简直是完美呀~~~ 然鹅!
Cat.prototype.childrenProp = '我是子类的原型属性!';
var parent = new Animal('父类');
console.log(parent.childrenProp);                           // 打印出'我是子类的原型属性!' what? 父类实例化的对象拥有子类的原型属性/方法,这是因为父类和子类使用了同一个原型

Advantages:
1. Create a subclass instance and pass parameters to the parent class constructor;
2. Instances of subclasses do not share the constructor and attributes of the parent class;
3. The constructor of the parent class is only called once;
Disadvantages : The parent class and the child class use the same prototype, causing the prototype modification of the child class to affect the parent class;

5. Parasitic combination inheritance (simply perfect)

function Cat(n) {
this.cName = n;                     
    Animal.call(this, this.cName);                          // 核心,把父类的实例方法属性指向子类;
}
var F = function(){};                                       // 核心,利用空对象作为中介;
F.prototype = Parent.prototype;                             // 核心,将父类的原型赋值给空对象F;
Cat.prototype = new F();                                    // 核心,将F的实例赋值给子类;
Cat.prototype.constructor = Cat;                            // 修复子类Cat的构造器指向,防止原型链的混乱;
tom.arr.push('Im tom');
console.log(black.arr);                                     // 打印出 [], 其方法和属性是每个子类实例所私有的;
tom.sing();                                                 // 打印出 '吹呀吹呀,我的骄傲放纵~~'; 子类继承了父类的原型方法及属性;
tom.pArr.push('publish');                                   // 修改继承于父类原型属性值 pArr;
console.log(black.pArr);                                    // 打印出 ['publish'], 父类的原型属性/方法 依旧是共享的;
Cat.prototype.childrenProp = '我是子类的原型属性!';
var parent = new Animal('父类');
console.log(parent.childrenProp);                           // undefind  父类实例化的对象不拥有子类的原型属性/方法;

Advantages: Perfect implementation of inheritance;
Disadvantages: Relatively complex implementation

YUI library attached to implement inheritance

function extend(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    hild.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;                          
}
// 使用
extend(Cat,Animal);

Child.uber = Parent .prototype; means to set an uber attribute for the child object, which directly points to the prototype attribute of the parent object. (Uber is a German word meaning "up" or "one level up.") This is equivalent to opening a channel on the child object, and you can directly call the parent object's method. This line is placed here just to achieve the completeness of inheritance and is purely for backup purposes.

ES6 inheritance method

class Animal{                                                // 父类
    constructor(name){                                       // 构造函数
        this.name=name;
    }
    eat(){                                                   // 实例方法
        return 'hello world';
    }
}
class Cat extends Animal{                                    // 子类
  constructor(name){
      super(name);                                           // 调用实现父类的构造函数
      this.pName = name;            
  }
  sing(){
     return '吹呀吹呀,我的骄傲放纵~~';
  }
}

Related articles:

Inheritance method of php constructor, php constructor inheritance

Related videos :

Geek Academy PHP object-oriented video tutorial

The above is the detailed content of A detailed introduction to the inheritance methods and pros and cons of js constructors (full code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn