ES6--面向对象
Posted lianglanlan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘)
以上是关于ES6--面向对象的主要内容,如果未能解决你的问题,请参考以下文章