ES6知识点整理class的应用

本文对比了JavaScript中使用class语法糖定义类与传统原型对象定义类的方法,详细介绍了两者之间的区别与联系,包括构造函数、原型链继承及成员方法定义等方面。

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

class

  • class 本身是个语法糖,主要为了考虑在编码上更加人性化
  • 内部有super,static,get 等关键词
  • 使用起来非常类似于后台语言

使用class进行类的实现应用

'use strict';

// User 类
class User {
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }

  static getName() {
    return 'User';
  }

  static getAge() {
    return this.age;
  }

  setName(name) {
    this.name = name;
  }

  setAge(age) {
    this.age = age;
  }

  get info() {
    return 'name:' + this.name + ' | age:' + this.age;
  }
}

// Manager 类
class Manager extends User{
  constructor(name,age,password){
    super(name,age);
    this.password = this.password;
  }

  changePwd(pwd) {
    return this.password = pwd;
  }

  get info() {
    var info = super.info; // 使用super继承父级 get
    return info + ' === new';
  }
}
// typeof User:  function  typeof Manager:  function
console.log('typeof User: ', typeof User, ' typeof Manager: ', typeof Manager); 

let manager = new Manager('Li', 22, '123456');
manager.setAge(23);
console.log(manager.info); // name:Li | age:23 === new
console.log(User.prototype);
console.log(Manager.prototype); 

在class之前使用原型对象定义类的应用

// 构造函数
function User(name,age) {
  this.name = name;
  this.age = age;
}
// 原型
User.prototype = {
  getName:function(){
    return 'User';
  },
  setName:function(name){
    this.name = name;
  },
  getAge:function(){
    return this.age;
  },
  setAge:function(age){
    this.age = age;
  }
}

// 取值函数和存执函数
Object.defineProperty(User.prototype,'info', {
  get() {
    return 'name:' + this.name + ' | age:' + this.age;
  }
});

var user = new User('Joh', 26);
console.log(user); // User {name: "Joh", age: 26}

// 子类
function Manager(name, age, password) {
  User.call(this, name, age);
  this.password = password;
}

Manager.__proto__ = User; // 继承静态方法
Manager.prototype = Object.create(User.prototype); // 继承prototype原型方法
Manager.prototype.changePwd = function (pwd) {
  this.password = pwd;
};
var manager = new Manager('Li', 22, '123456');
manager.setAge(23);
console.log(manager.info); // name:Li | age:23
console.log(User.prototype); // 不变
console.log(Manager.prototype); // {changePwd:function(){}, info:"name:undefined | age:undefined", __proto__:指向Manager.prototype}

使用 class 定义的类不被提升,需按顺序执行

正常:

let user = new class User {
  constructor(name) {
    this.name = name;
  }
}('Joh');
console.log(user); // User {name: "Joh"}

错误:

var man = new Man(); // 此处报错,使用class声明的类不会被提升 Uncaught ReferenceError: Man is not defined
class Man {
  constructor(name){
    this.name = name;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wang's Blog

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

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

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

打赏作者

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

抵扣说明:

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

余额充值