ES6--面向对象
类
ES5通过构造函数生成实例对象
function User(name, pass) { this.name = name this.pass = pass } User.prototype.log = function () { console.log('name = ' + this.name + ', pass = ' + this.pass) } var user1 = new User('xiaoming', '12356') user1.log() //name = xiaoming, pass = 12356
ES6引入class(类)概念与constructor构造方法。定义“类”的方法时,前面不需要加 function 关键字。方法之间不需要逗号分隔,加了会报错。
class User { constructor(name, pass) { this.name = name this.pass = pass } log() { console.log(`name = ${this.name} , pass = ${this.pass}`) } } let user1 = new User('xiaoming', '12356') user1.log() //name = xiaoming , pass = 12356
继承
ES5继承
function VipUser(name, pass, level) { User.call(this, name, pass) this.level = level } VipUser.prototype = new User(); VipUser.prototype.constructor = VipUser VipUser.prototype.logLevel = function () { console.log('level = ' + this.level) } var v1 = new VipUser('xiaoming', '123456', '5') v1.log() v1.logLevel()
ES6继承(extends和super)
class VipUser extends User { constructor(name, pass, level) { super(name, pass) this.level = level } logLevel() { console.log(`level = ${this.level}`) } } let v1 = new VipUser('xiaoming', '1234', '5')
静态方法和静态属性
所有在类中定义的方法,都会被实例继承。如果在一个方法前加上 static 关键字,该方法就不会被实例继承,而是通过类来调用,这种方法或属性被称为静态方法或属性
静态属性的对立面是实例属性(只能通过类的实例来调用)
ES5静态属性与实例属性
function Person(name) { this.name = name //实例属性,挂载在实例上 } //静态属性info,挂载在构造函数(类)上 Person.info = { name: 'zs', age: 20 }
ES6静态属性