ES6 中的类

ES6 和 TypeScript 中的类,学习记录。接上一篇:JavaScript 中的类

ES6 中的类


一、 Class 的基本语法

ES6 引入了 Class(类)这个概念作为对象的模版。通过 class 关键字可以定义类。

基本上,ES6 中的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰,更像面向对象编程的语法而已。

class Point {
   
	constructor(x, y) {
   
		this.x = x;
		this.y = y;
	}
	toString() {
   
		return '(' + this.x + ',' + this.y + ')';
	}
}
1. constructor 构造方法

constructor 方法是类的默认方法,通过 new 命令生成对象实例时自动调用该方法。一个类必须有 constructor 方法,如果没有显示定义,一个空的 constructor 方法会被默认添加。

类必须通过 new 来调用,否则会报错。这是它跟普通构造函数的一个主要区别。
类不存在变量提升(hoist),这一点和 ES5 完全不同。

构造方法中 this 上的属性是定义在实例上的属性,this 就是指向实例的。还有一种定义实例属性的方法,就是直接定义类的属性成员:
在这里插入图片描述

2. this 的指向

类的方法内部如果含有 this ,它将默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能会报错。

class Logger {
   
  printName(name = 'there') {
   
    this.print(`Hello ${
     name}`);
  }

  print(text) {
   
    console.log(text);
  }
}

const logger = new Logger();
const {
    printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined

解决方法:

  • 在构造函数中绑定 this
    class Logger {
         
      constructor() {
         
        this.printName = this.printName.bind(this);
      }
    
      // ...
    }
    
  • 使用尖头函数:箭头函数内部的 this 总是指向定义时所在的对象。
    class Obj {
         
      constructor() {
         
        this.getThis = () => this;
      }
    }
    
    const myObj = new Obj();
    myObj.getThis() === myObj // true
    
  • 使用 Proxy ,在获取方法的时候自动绑定 this
    function selfish (target) {
         
      const cache = new WeakMap();
      const handler = {
         
        get (target, key) {
         
          const value = Reflect.get(target, key);
          if (typeof value !== 'function') {
         
            return value;
          }
          if (!cache.has(value)) {
         
            cache.set(value, value.bind(target));
          }
          return cache.get(value);
        }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值