你的位置:首页 > Java教程

[Java教程]es5 和 es6 class


// ES5function User(name,age) {  this.name = name;  this.age = age;}// 静态方法User.getClassName = function(){  return 'User'}User.prototype.changeName = function(name){  this.name = name}User.prototype.changeAge = function(Age){  this.Age = Age}Object.defineProperty(User.prototype,'info',{  get(){    return 'name'+this.name+'age'+this.age  }})// 子类function Manager(name,age,password){  User.call(this,name,age);  this.password = password}// 继承静态方法Manager.__proto__ = User// 继承原型方法Manager.prototype = User.prototype;//添加新方法Manager.prototype.changePassword = function(pwd){  this.password = password}var manager = new Manager('leo',22,'123');manager.changeName('zengliang');console.log(User.name) //Userconsole.log(manager.name) //zengjiangfunction test(){  console.log("1")}console.log(test.name) //test

ES6

// function User(name,age) {//   this.name = name;//   this.age = age;// }class User {  constructor(name,age){    this.name = name;    this.age = age;      }  // // 静态方法  // User.getClassName = function(){  //   return 'User'  // }   static getClassName(){    return 'User'  }  // 方法的定义  // User.prototype.changeName = function(name){  //   this.name = name  // }  // User.prototype.changeAge = function(Age){  //   this.Age = Age  // }  changeName(name){    this.name = name  }  changeAge(age){    this.age = age  }  // 自定义属性  // Object.defineProperty(User.prototype,'info',{  //   get(){  //     return 'name'+this.name+'age'+this.age  //   }  // })  get info(){    return 'name'+this.name+'age'+this.age  }}// 子类// function Manager(name,age,password){//   User.call(this,name,age);//   this.password = password// }class Manager extends User{  // 和call的区别,call先创建自身对象  constructor(name,age,password){    // super先创建父对象 必须    super(name,age);    this.password = password  }  // //添加新方法  // Manager.prototype.changePassword = function(pwd){  //   this.password = password  // }  changePassword(password){    this.password = password  }  get info(){    var info = super.info;    console.log(info)  }}// 下面的静态方法跟原型方法已经继承了,无须写其他的// // 继承静态方法// Manager.__proto__ = User// // 继承原型方法// Manager.prototype = User.prototype;console.log(typeof User,typeof Manager)//function function// var manager = new Manager('leo',22,'123');// manager.changeName('zengliang');// console.log(User.name) //User// console.log(manager.name) //zengjiang// function test(){//   console.log("1")// }// console.log(test.name) //test

不会提升

// // 立即执行// let user = new class User{//   constructor(name){//     this.name = name//   }// }('zengliang');// console.log(user)// 会报错,因为不会提升// var user = new User()// class User{//   constructor(name){//     this.name = name//   }// }