javascript 类的区别
Posted shijiu520
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 类的区别的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段12——JavaScript的Promise对象