ES6中Class类的详解

概述

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

严格模式

    类和模块的内部,默认就是严格模式,所以不需要使用 use strict 指定运行模式

类的声明

定义一个类的一种方法是使用一个类声明,即用带有class关键字的类名(这里是“Rectangle”)
函数名和实例化构造名相同且大写(非强制)

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

函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。需要先进行声明,再去访问,否则会报错

var person= new Person()
class Person {
	constructor(x, y) {
    this.x = x
    this.y = y
  }
}
// Personis not defined

类声明不可以重复

class Person {}
class Person {}
// TypeError Identifier 'Person' has already been declared

类必须使用 new 调用,否则会报错。这是它跟普通构造函数的一个主要区别,就是后者不用 new 也可以执行

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 命令生成对象实例时,自动调用该方法(默认返回实例对象 this)。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。一个类只能拥有一个名为 “constructor” 的特殊方法,如果类包含多个 constructor 的方法,则将抛出 一个 SyntaxError 。

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

注意:

  1. 在类中声明方法的时候,方法前不加 function 关键字
  2. 方法之间不要用逗号分隔,否则会报错
  3. 类的内部所有定义的方法,都是不可枚举的(non-enumerable)
  4. 一个类中只能拥有一个 constructor 方法

静态方法

    静态方法可以通过类名调用,不能通过实例对象调用,否则会报错

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

猜你喜欢

转载自blog.csdn.net/fu983531588/article/details/89499461