阅读 87

ES6 class类的使用笔记

class类

JavaScript语言的传统方法是通过构造函数,定义并生成新对象。function即使对象,对象既是function,没有class的概念。ES6提供了更接近传统语言的写法,比如JAVA、PHP等后端语言,引入了class(类)的概念,作为对象的模板。通过class关键字,可以定义类。
可以实现: 单例模式,访问器属性、静态方法、extends继承。

1. class与es5构造函数的区别

es5构造函数

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.show = function() {
  console.log(this.name, this.age)
}
let person = new Person("张三", 20);
person.show();  // 张三  20

class 写法一:类声明

class Person {
  // 构造函数
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  // 方法
  show() {
    console.log(this.name, this.age)
  }
}
let person = new Person("李四", 22);
person.show(); // 李四  22

class写法二:表达式

let Person = calss{
  // 构造函数
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  // 方法
  show() {
    console.log(this.name, this.age)
  }
}
let person = new Person("李四", 22);
person.show(); // 李四  22

2. class 单例模式

let person = new class{
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  show() {
    console.log(this.name, this.age)
  }
}("张三", 20)
person.show(); // 张三  20

3. class访问器属性set()与get()

class Person{
  construction(name, age) {
    this.name = name;
    this.age = age;
    this.text = "";
  }
  // set 监听属性值的变化,属性值一旦发生变化,立即触发set方法
  set age( val) {
    if (val >= 18) {
      this.text = "成年"
    } else {
      this.text = "未成年"
    }
  }
  // get 获取值
  get age() {
    return this.text;
  }
}
let person = new Person("张三", 17);
console.log(person.text)
person.age = 20;
console.log(person.text)

4. class的静态方法

在class没有在实例化的情况下可以直接调用方法。
静态方法的有点:
1.不用创建实例即可调用
2.静态方法效率比实例化高,static方法只会被初始化一次,不会因为实例化而多次初始化,节省每次创建对象的内存空间。

class Person{
  construtor(name, age) {
    this.name = name;
    this.age = age;
  }
  static show() {
    console.log("我是静态方法")
  }
}
Person.show();

5. extends继承

子类可以继承父类的属性和方法,如果子类没有构造函数,则默认继承父类的构造函数,如果子类有构造函数则使用super()方法调用父类构造函数。子类可以重写父类的方法,如果子类需要原封不动调用父类方法则需要使用super()方法。

// 父类(基类)
class Person{
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  run() {
    console.log("跑步");
  }
}
// 子类(派生类)  
class Superman extends Person{
  constructor(name) {
    super(name);  // 使用super()方法,解决继承构造冲突,调用父类构造函数
   }
  run() {
    super.run(); // 使用super调用父类的方法
    // console.log(this.name + "在跑步");
  }
}
let person = new Superman("人类");
console.log(person.name);
person.run();

作者:空空雨夜

原文链接:https://www.jianshu.com/p/1ef614a3af95

文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐