栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

ES6 class的应用实例分析

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ES6 class的应用实例分析

本文实例讲述了ES6 class的应用。分享给大家供大家参考,具体如下:

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;
 }
}

更多关于Javascript相关内容可查看本站专题:《javascript面向对象入门教程》、《Javascript查找算法技巧总结》、《Javascript错误与调试技巧总结》、《Javascript数据结构与算法技巧总结》、《Javascript遍历算法与技巧总结》及《Javascript数学运算用法总结》

希望本文所述对大家Javascript程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/74948.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号