ES6中Class类的理解

在ES6中,class (类)经过 class 关键字定义类。它能够被看做一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
    类其实是个“特殊的函数”,就像你可以定义的函数表达式和函数声明同样,类语法有两个组成部分:类表达式和类声明。编程

类表达式和类声明

类声明:

class Person{
constructor(x,y){
this.x = x;
this.y = y
}
}函数

总结:this

  • 类声明的时候,类名必需要大写
  • 函数声明和类声明之间的一个重要区别是函数声明会提高,类声明不会。须要先进行声明,再去访问,不然会报错prototype

    var person= new Person()
           class Person {
               constructor(x, y) {
               this.x = x
               this.y = y
             }
           }
           // Personis not defined
  • 类声明不能够重复
  • 类必须使用 new 调用,不然会报错code

    class Person {
           constructor(x, y) {
           this.x = x
           this.y = y
         }
       }
       Person()
       // TypeError Class constructor Person cannot be invoked without 'new'

类表达式(类定义)

类表达式能够是被命名的或匿名的对象

* 匿名类 */ 
    let Person = class {
      constructor(x, y) {
        this.x = x
        this.y = y
      }
    }

    /* 命名的类 */ 
    let Person = class Person {
      constructor(x, y) {
        this.x = x
        this.y = y
      }
    }

类的方法

constructor方法

 constructor 方法是类的默认方法,在new 命令生成对象实例时,会自动调用constructor方法,同时默认返回实列对象的this;原型

一个类必须有 constructor 方法,若是没有显式定义,一个空的 constructor 方法会被默认添加。一个类只能拥有一个名为 “constructor” 的特殊方法,若是类包含多个 constructor 的方法,则将抛出 一个 SyntaxError 。it

class Person {
   constructor(x, y) {
    this.x = x    // 默认返回实例对象 this
    this.y = y
  }
  toString() {
    console.log(this.x + ', ' + this.y)
  }
}

静态方法

在类对象的内部的方法【constructor除外】前面加上static后,该方法就是静态方法了io

注意:静态方法能够经过类名调用,不能经过实例对象调用,不然会报错console

class Person {
    static sum(a, b) {
        console.log(a + b)
    }
}
var p = new Person()
Person.sum(1, 2)  // 3
p.sum(1,2)     //  TypeError p.sum is not a function

原型方法

  • 类的全部方法都定义在类的 prototype 属性上面,
  • 在类的实例上面调用方法,其实就是调用原型上的方法
  • 原型方法能够经过实例对象调用,但不能经过类名调用,会报错
class Person {
        constructor() {
            // 默认返回实例对象 this
        }
        sum() {

        }
        toString() {
            console.log('123456')
        }
    }
    // 给 Person 的原型添加方法
    Person.prototype.toVal = function() {
        console.log('I am is toVal')
    }

    // 等同于
    Person.prototype = {
      constructor() {},
      sum() {},
      toString() {}
    }

    var p = new Person()
    p.toString()       // 123456
    p.toVal()          // I am is toVal
    Person.toString()  // TypeError Person.toStringis not a function
    Person.toVal()  // TypeError Person.toVal is not a function

实例方法

实例方法也能够经过实例对象调用,但一样不能经过类名调用,会报错

class Person {
        constructor() {
            this.sum = function(a, b) {
                console.log(a + b)
            }
        }
    }
    var p = new Person()
    p.sum(1,2)       // 3
    Person.sum(1,2)  // TypeError Person.sum is not a function

总结方法

  • 除了静态方法是用类名调用的,其余方法都是用实例对象调用的;
  • 类的全部方法其实都是定义在类的原型属性上的
  • 生成对象实例的时候会自动调用constructor方法,而且返回实列对象的this
相关文章
相关标签/搜索