ES6—Class

1. Constructor and Prototype

1.1 Overview

In typical OOP languages ​​(such as Java), there is the concept of classes. Classes are templates of objects, and objects are instances of classes. But before ES6, JS did not introduce the concept of classes.

ES6, full name ECMAScript 6.0, released on June 2015. Before ES6, objects were not created based on classes, but used a 构造函数special function called a special function to define their characteristics.

There are three ways to create an object:

  1. Object literal
  2. new Object()
  3. Custom constructor
   // 1.利用new Object() 创建对象
    var obj1 = new Object();

    // 2. 利用 对象字面量创建对象
    var obj2 = {
    
    };
    
    // 3. 利用构造函数创建对象
    function Star(uname, age) {
    
    
      this.uname = uname;
      this.age = age;
      this.sing = function() {
    
    
        console.log('我会唱歌');
      }
    }
    
    var ldh = new Star('刘德华', 18);
    console.log(ldh); // Star
    ldh.sing(); // 我会唱歌

1.2 Constructor

The constructor is a special function, mainly used to initialize the object, that is, to assign initial values ​​to the object member variables, and it is used together with new. We can extract some common attributes and methods from the object, and then encapsulate them into this function.

In JS, pay attention to the following two points when using the constructor:

  • The constructor is used to create a certain type of object, and its first letter should be capitalized
  • Constructor only makes sense to use with new

New will do four things during execution

  • Create a new empty object in memory
  • Let this point to this new object
  • Execute the code in the constructor to add properties and methods to this new object
  • Return this new object (so there is no need to return in the constructor)

Some members can be added to the JavaScript constructor, either on the constructor itself, or on this inside the constructor. The members added by these two methods are called static members and instance members respectively

  • Static members: members added on the constructor itself become静态成员,只能由构造函数本身来访问

  • Instance member: the object member created inside the constructor is called实例成员,只能由实例化的对象来访问

function Star(uname, age) {
    
    
  this.uname = uname;
  this.age = age;
  this.sing = function() {
    
    
    console.log('我会唱歌');
  }
}
    
var ldh = new Star('刘德华', 18);
var zxy = new Star('张学友', 19);
// 实例成员就是构造函数内部通过this添加的成员 uname age sing 是实例成员
// 实例成员只能通过实例化的对象来访问

console.log(ldh.uname); // 刘德华
ldh.sing(); // 我会唱歌
zxy.sing(); // 我会唱歌
console.log(ldh.sing===zxy.sing) // false
console.log(Star.uname); // undefined, 不可以通过构造函数来访问实例成员

// 在构造函数本身上添加的成员称为静态成员
Star.sex = '男'
console.log(Star.sex); // 男
console.log(ldh.sex); // undefined

1.3 The problem with the constructor

The constructor works well, but存在浪费内存的问题

Because the method inside is that complex data types need to open up new memory space, and every time an object is instantiated, a space must be opened up, which causes a waste of memory space, so there is a constructor function prototype

1.4 Constructor prototype

The function assigned by the constructor through the prototype is all objects 共享的.

JavaScript stipulates that 每一个构造函数都有一个prototype属性, points to another object. Note that this prototype is an object, and all the properties and methods of this object will be owned by the constructor.

可以把那些不变的方法,直接定义在prototype对象上,这样所有对象的实例就可以共享这些方法。

  1. What is the prototype?

    An object, also called prototype as a prototype object, each constructor has a prototype

  2. What is the role of prototypes?

    共享方法

     // 1. 利用构造函数创建对象
        function Star(uname, age) {
          
          
          this.uname = uname;
          this.age = age;
        }
        Star.prototype.sing = function() {
          
          
          console.log('我会唱歌');
        }
        
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
      
        console.log(Star.prototype);
        ldh.sing(); // 我会唱歌
        zxy.sing(); // 我会唱歌
        console.log(ldh.sing===zxy.sing) // true
    

1.5 Object prototype_ proto _

Objects will have an attribute __proto__ that points to the prototype object of the constructor. The reason why the object can use the properties and methods of the prototype object of the constructor is because the object has the _ proto _ prototype.

  • _ proto _ Object prototype and prototype object prototype are equivalent

Method search rules:

First find out if the object has this method, if there is, execute it, if not, find out if there is this method on the prototype object prototype of the constructor

1.6 constructor Constructor

Both the object prototype (_ proto _) and the constructor function prototype object (prototype) have a constructor attribute, which we call the constructor function because it refers to the constructor itself.

In many cases, you need to manually use the constructor attribute to point back to the original constructor

// 当需要添加多个方法时,可以如下简写
Star.prototype = {
    
    
    sing: function() {
    
    },
    movie: function() {
    
    }
    // 但是这样写,就改变了原来的原型,所以需要利用constructor指回原来的构造函数
    constructor:Star
}

1.7 The relationship between constructor, instance, and prototype object

Insert picture description here

1.8 Prototype chain

As long as it is an object, it has a prototype _ proto _

Insert picture description here

1.9 JavaScript member lookup mechanism (rules)

  • When accessing an object's properties (including methods), first look for the one 对象自身without the property.

  • If not, find its prototype (that is, the point pointed to by __proto__ prototype原型对象).

  • Find the prototype of the prototype object if it is not there yet ( Object的原型对象)

  • And so on until you find the Object ( null)

1.10 The prototype object this points to

  • In the constructor, this points to the object instance
  • The this in the prototype object function points to the instance object

1.11 Extend built-in objects

The original built-in object can be extended and customized through the prototype object. For example, add a custom even number function to the array.

// 原型对象的应用 扩展内置对象方法
console.log(Array.prototype);
Array.prototype.sum = function() {
    
    
  var sum = 0;
  for(var i = 0; i < this.length; i++) {
    
    
    sum += this[i];
  }
  return sum;
}
var arr = [1, 2, 3];
console.log(arr.sum()); // 6
    

2. Inheritance

Before ES6, extends inheritance was not provided. We can 构造函数+原型implement inheritance through object simulation, which is called组合继承

2.1 call()

Call this function, and modify the this point when the function is running

fun.call(thisArg,arg1,arg2, ...)

  • thisArg: the object to which the function this is currently called
  • arg1, arg2: other parameters passed
    function fn(x,y) {
    
    
      console.log('我想喝手磨咖啡');
      console.log(this); 
      console.log(x+y);
    }
    var o = {
    
    
      name:"andy"
    }
    // 1. call()可以调用函数
    fn.call(); // 我想喝手磨咖啡  Window  NaN
    // 2. call() 可以改变this指向。此时指向o对象
    fn.call(o,1,2); //  我想喝手磨咖啡  Object  3

2.2 Borrowing the constructor to inherit the properties of the parent type

Core principle: point this of the parent type to this of the subtype through call, so that the subtype can inherit the properties of the parent type

    // 1. 父构造函数
    function Father(uname,age) {
    
    
      // this 指向父构造函数的对象实例
      this.uname = uname;
      this.age = age;
    }
    // 2. 子构造函数
    function Son(uname,age) {
    
    
      // this 指向子构造函数的对象实例
      Father.call(this, uname, age);
    }
    var son = new Son('ldh', 18);
    console.log(son);

2.3 Borrowing prototype objects to inherit parent type methods

 // 1. 父构造函数
    function Father() {
    
    
      ...
    }
    Father.prototype.money = function() {
    
    
      console.log(1000);
    }
    // 2. 子构造函数
    function Son() {
    
    
      ...
    }
    //Son.prototype = Father.prototype; // 这样直接赋值会有问题,如果修改了子原型对象,父原型对象也一起被修改
    Son.prototype = new Father();
        
    // 如果利用对象的形式修改了原型对象,别忘了利用constructor指回原来的构造函数
    Son.prototype.constructor = Son;
        
    // 这个是子构造函数专门的方法
    Son.prototype.exam = function() {
    
    
      console.log('孩子要考试');
    }
    console.log(son);
    console.log(Father.prototype);
    console.log(Son.prototype.constructor);

3. The nature of the class

  1. The essence of class is still function, you can simply think that class is another way of writing constructor

Before ES6, object-oriented programming was realized through constructor + prototype

  • The constructor has a prototype object prototype
  • The constructor of the prototype object prototype has a constructor that points to the constructor itself
  • Constructor can add methods through prototype object
  • The instance object created by the constructor has __proto__ prototype pointing to the prototype object of the constructor

ES6 implements object-oriented programming through classes

class Star {
    
    
    
}
// 1. 类有原型对象prototype
console.log(Star.prototype);
// 2. 类原型对象prototype里面有constructor 指向类本身
console.log(Star.prototype.constructor);
// 3. 类可以通过原型对象添加方法
Star.prototype.sing = function() {
    
    
    console.log('冰雨')
}
// 4. 类创建的实例对象有__proto__原型指向类的原型对象
var ldh = new Star();
console.dir(ldh); // 
console.log(ldh.__proto__ === Star.prototype); // true

Summary: A class has the characteristics of a constructor, that is, a class is another way of writing a constructor. Therefore, most of the functions of ES6 classes can be achieved by ES5. The new class writing only makes the writing of object prototypes clearer and more like the syntax of object-oriented programming.

Guess you like

Origin blog.csdn.net/qq_46178261/article/details/107160782