一:面向对象
一般面向对象的写法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //一般面向对象的写法 function User(name, pass) { this.name = name; this.pass = pass; } User.prototype.showName = function() { console.log(this.name); } User.prototype.showPass = function() { console.log(this.pass); } var a = new User("wangting", "123456"); a.showName(); a.showPass(); </script> </html>
存在问题 : User既是构造函数,又是类,傻傻分不清
打印结果
ES6面向对象写法
好处:
1:class关键字,构造器 constructor和类User分开写
2:class里面直接写方法,方法不需要再外挂出去了
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //ES6面向对象写法 class User { constructor(name, pass) { this.name = name; this.pass = pass; } showName() { console.log(this.name); } showPass() { console.log(this.pass); } } var a = new User("wangting", "123456"); a.showName(); a.showPass(); </script> </html>
打印结果
二:继承
继承一个已有类,扩展它的功能
一般的继承的写法(es5继承方法),这是在日常开发中经常能看到的写法。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //一般写法 function User(name, pass) { this.name = name; this.pass = pass; } User.prototype.showName = function() { console.log(this.name); } User.prototype.showPass = function() { console.log(this.pass); } //继承方法 function Children(name, pass, level) { User.call(this, name, pass); this.level = level; } //方法 Children.prototype = new User(); Children.prototype.constructor = Children; Children.prototype.showLevel = function() { console.log(this.level) } var a = new Children("wangxiaoting", "123", 3); a.showName(); a.showPass(); a.showLevel(); </script> </html>
打印结果:
ES6的继承:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //ES6面向对象写法 class User { constructor(name, pass) { this.name = name; this.pass = pass; } showName() { console.log(this.name); } showPass() { console.log(this.pass); } } //es6的继承(重点) class Children extends User { constructor(name, pass, level) { //继承父级属性 //同时执行父类的构造函数 super(name, pass); //继续写自己这一层该有的属性 this.level = level; } //关于方法,就不需要像旧版new出来xx给.prototype了,因为 extends已经扩展完成了 //直接写就行 showLevel() { console.log(this.level); } } let c = new Children('wangxiaoting', '123', 23); c.showName(); c.showPass(); c.showLevel(); </script> </html>
打印结果: