一文了带您了解 ES6 Class 用法

👨‍⚕️ 主页: gis分享者
👨‍⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅!
👨‍⚕️ 收录于专栏:前端工程师



一、✈️概述

  • ES6中的class是基于JavaScript中的一个强大的属性,也就是原型属性prototype,由这个属性改良得来的一种语法糖。
  • 在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
  • class 的本质是 function

二、✈️用法

2.1 ✈️基础用法

class 定义

// 匿名类
let Book = class {
    constructor(a) {
        this.a = a;
    }
}
// 命名类
let Book = class Book {
    constructor(a) {
        this.a = a;
    }
}

注意:类定义不会被提升,必须在访问前对类进行定义,否则就会报错。
类中方法不需要 function 关键字,方法间不能加分号。
class的主体
属性prototype, 类的所有方法都定义在类的prototype属性上面

// 通过prototype动态添加方法
Book.prototype={
    //methods
}
// 通过Object.assign动态添加方法
Object.assign(Book.prototype,{
    //methods
})

ES6 中规定,class 内部只有静态方法,没有静态属性。

class Book {
	// 新提案, 不可用
    static a = 2;
}
// 目前可行写法
Book.b = 2;

// 公共属性
class Book{}
Book.prototype.a = 2;

// 实例属性,定义在实例对象( this )上的属性。
class Book {
    pro = 2;
    constructor () {
        console.log(this.pro);
    }
}

// name 类名属性
let Book = class Exam {
    constructor(a) {
        this.a = a;
    }
}
console.log(Book.name); // Exam
 
let Book = class {
    constructor(a) {
        this.a = a;
    }
}
console.log(Book.name); // Book

方法

/** constructor 方法是类的默认方法,创建类的实例化对象时被调用。**/
class Book{
    constructor(){
      console.log('我是constructor方法');
    }
}
new Book(); // 我是constructor方法

/** 返回对象 **/
class Test {
    constructor(){
        // 默认返回实例对象 this
    }
}
console.log(new Test() instanceof Test); // true
 
class Book {
    constructor(){
        // 指定返回对象
        return new Test();
    }
}
console.log(new Book() instanceof Book); // false

/** 静态方法 **/
class Test{
    static sum(a, b) {
        console.log( a + b);
    }
}
Test.sum(1, 3); // 4

/** 原型方法 **/
class Test {
    sub(a, b) {
        console.log(a - b);
    }
}
let test = new Test();
test.sub(2, 1); // 1

/** 实例方法 **/
class Test {
    constructor() {
    }
    sum = (a, b) => {
            console.log(a + b);
    }
}
// 或者
class Test {
    constructor() {
        this.sum = (a, b) => {
            console.log(a + b);
        }
    }
}

实例化

// class 的实例化必须通过 new 关键字
class Test {}
let test = Test(); 
// Class constructor Example cannot be invoked without 'new'

decorator
装饰器,是一个函数,用来修改类的行为,用于扩展类属性和类方法

function testable(target) {
    target.isTestable = true;
}
@testable
class Example {}
Example.isTestable; // true
// 多个参数嵌套实现
function testable(isTestable) {
    return function(target) {
        target.isTestable=isTestable;
    }
}
@testable(true)
class Example {}
Example.isTestable; // true

方法修饰
3个参数:target(类的原型对象)、name(修饰的属性名)、descriptor(该属性的描述对象)

class Book {
    @writable
    sum(a, b) {
        return a + b;
    }
}
function writable(target, name, descriptor) {
    descriptor.writable = false;
    return descriptor; // 必须返回
}

// 修饰器执行顺序,由外向内进入,由内向外执行。
class Book {
    @logMethod(1)
    @logMethod(2)
    sum(a, b){
        return a + b;
    }
}
function logMethod(id) {
    console.log('evaluated logMethod' + id);
    return (target, name, desctiptor) => console.log('excuted logMethod ' + id);
}
// evaluated logMethod 1
// evaluated logMethod 2
// excuted logMethod 2
// excuted logMethod 1

2.2 ✈️封装与继承

// getter / setter
// 定义
class Example{
    constructor(a, b) {
        this.a = a; // 实例化时调用 set 方法
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this.a;
    }
    set a(a){
        console.log('setter');
        this.a = a; // 自身递归调用
    }
}
let exam = new Example(1,2); // 不断输出 setter ,最终导致 RangeError
class Example1{
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this._a;
    }
    set a(a){
        console.log('setter');
        this._a = a;
    }
}
let exam1 = new Example1(1,2); // 只输出 setter , 不会调用 getter 方法
console.log(exam1._a); // 1, 可以直接访问

// getter 不可单独出现
class Book {
    constructor(a) {
        this.a = a; 
    }
    get a() {
        return this.a;
    }
}
let exam = new Book(1); // Uncaught TypeError: Cannot set property // a of #<Example> which has only a getter

// getter 与 setter 必须同级出现
class Father {
    constructor(){}
    get a() {
        return this._a;
    }
}
class Child extends Father {
    constructor(){
        super();
    }
    set a(a) {
        this._a = a;
    }
}
let test = new Child();
test.a = 2;
console.log(test.a); // undefined
 
class Father1 {
    constructor(){}
    // 或者都放在子类中
    get a() {
        return this._a;
    }
    set a(a) {
        this._a = a;
    }
}
class Child1 extends Father1 {
    constructor(){
        super();
    }
}
let test1 = new Child1();
test1.a = 2;
console.log(test1.a); // 2

2.3 ✈️继承

// 通过 extends 实现类的继承
class Child extends Father { ... }

// 子类 constructor 方法中必须有 super ,且必须出现在 this 之前。
class Father {
    constructor() {}
}
class Child extends Father {
    constructor() {}
    // or 
    // constructor(a) {
        // this.a = a;
        // super();
    // }
}
let test = new Child(); // Uncaught ReferenceError: Must call super 
// constructor in derived class before accessing 'this' or returning 
// from derived constructor

// 调用父类构造函数,只能出现在子类的构造函数
class Father {
    test(){
        return 0;
    }
    static test1(){
        return 1;
    }
}
class Child extends Father {
    constructor(){
        super();
    }
}
class Child1 extends Father {
    test2() {
        super(); // Uncaught SyntaxError: 'super' keyword unexpected     
        // here
    }
}


// 调用父类方法, super 作为对象,在普通方法中,指向父类的原型对象,在静态方法中,指向父类
class Child2 extends Father {
    constructor(){
        super();
        // 调用父类普通方法
        console.log(super.test()); // 0
    }
    static test3(){
        // 调用父类静态方法
        return super.test1+2;
    }
}
Child2.test3(); // 3

// 不可继承常规对象。
var Father = {
    // ...
}
class Child extends Father {
     // ...
}
// Uncaught TypeError: Class extends value #<Object> is not a constructor or null
 
// 解决方案
Object.setPrototypeOf(Child.prototype, Father);
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gis分享者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值