ES2015 class

本文介绍了ES2015引入的类(class)关键字,对比了实例方法和静态方法的区别,并详细阐述了如何在ES2015中使用extends关键字进行类的继承,包括之前使用原型实现继承的方式和新语法的改进。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、类 class

ES2015以前

ECMAScript都是通过定义函数和定义原型对象来实现类

// 比如定义一个Person类

// 先定义一个函数,作为类的构造函数
function Person(name){
  this.name = name;
}
Person.prototype.say = function(){
  console.log(`say ${this.name}`)
}

ES2015以后

新增了class关键词来声明一个类

class Person{
  // 如果需要在构造函数中做一些额外的逻辑
  
  // constructor就是当前这个类的构造函数
  constructor(name){
    // 可以用this 访问当前类的实例对象
    this.name = name
  }
  // 如果需要为这个类定义一些实例方法
  say(){
    console.log(`say ${this.name}`)
  }
}

const p = new Person('tom')
p.say()

二、实例方法 VS 静态方法

在类中的方法通常分为实例方法静态方法

  • 实例方法:通过这个类构造的实例对象去调用

  • 静态方法:通过类本身去调用

ES2015以前,实现静态方法是直接在构造函数上挂载方法

ES2015中新增了添加静态成员的static关键词

class Person{
  constructor(name){
    this.name = name
  }
  say(){
    console.log('实例方法say的this指向:',this) 
    console.log(`say ${this.name}`)
  }
  static create(name){
    console.log('静态方法create的this指向:',this) // [Function: Person]
    return new Person(name)
  }
}

const tom = Person.create('tom')
tom.say()

在这里插入图片描述

class Person{
  constructor(name){
    this.name = name
  }
  say(){
    console.log('实例方法say的this指向:',this) 
    console.log(`say ${this.name}`)
  }
  static create(name){
    console.log('静态方法create的this指向:',this) // [Function: Person]
    return new Person(name)
  }
}


const luyu = new Person('luyu')
luyu.say()

在这里插入图片描述

三、继承 extends

继承是面向对象中一个很重要的特性,通过继承就能抽象出来相似的类中重复的地方

ES2015以前,大多数情况都是使用原型的方式实现继承

ES2015中,有一个专门用于类的继承的关键字:extends


class Person{
  constructor(name){
    this.name = name
  }
  say(){
    console.log(`say ${this.name}`)
  }
}
// 继承自Person,Student 中就会有Person中所有的成员
class Student extends Person {
  // Student 构造函数中接收2个参数
  constructor(name,number) {
    
    // name 参数在父类中也需要用到
    // super对象 始终指向父类,调用它就是调用了父类的构造函数
    super(name)
    this.number = number;
  }

  // 定义Student特有的成员
  hello(){
    super.say();
    console.log(`my school number is ${this.number}`)
  }
}

const tom = new Student('tom','100')
tom.hello()


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值