首页 > 代码库 > javascript 类的区别
javascript 类的区别
javascript 新式类与旧式类的区别:
es6:
//es6 ‘use strict‘ class User{ constructor(name,age){ this.name = name; this.age = age; } //静态方法 static getClassName(){ return ‘User‘; } changeName(name){ this.name = name; } changeAge(age){ this.age = age; } get info(){ return ‘name:‘+this.name+‘ | age:‘+this.age; } } class Manager extends User{ constructor(name,age,password){ super(name,age); this.password = password; } changePassword(password){ this.password = password; } } console.log(typeof User); console.log(typeof Manager)
es5:
//传统类 function 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 = pwd; } var manager = new Manager(‘leo‘,22,‘123‘); console.log(manager); manager.changeName(‘zheng liang‘) console.log(manager);
javascript 类的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。