面向对象原来写法
- 类和构造函数一样
- 属性和方法分开写的
// 老版本 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 u1 = new User(‘able‘, ‘1233‘) u1.showName() u1.showPass() // 老版本继承 function VipUser(name, pass, level) { User.call(this, name, pass) this.level = level } VipUser.prototype = new User() VipUser.prototype.constructor = VipUser VipUser.prototype.showLevel = function () { console.log(this.level) } var v1 = new VipUser(‘blue‘, ‘1234‘, 3) v1.showName() v1.showLevel()
新版面向对象
- 有了 class 关键字、构造器
- class 里面直接加方法
- 继承,super 超类==父类
class User { constructor(name, pass) { this.name = name this.pass = pass } showName() { console.log(this.name) } showPass() { console.log(this.pass) } } var u1 = new User(‘able2‘, ‘111‘) u1.showName();// able2
u1.showPass(); // 111 // 新版本继承 class VipUser extends User { constructor(name, pass, level) { super(name, pass) this.level = level } showLevel(){ console.log(this.level) } } v1 = new VipUser(‘blue‘, ‘123‘, 3) v1.showLevel();// 3
原文地址:https://www.cnblogs.com/sylys/p/11641943.html
时间: 2024-11-08 22:58:43