ES6中类的定义和基本使用
类的定义和基本用法
// es6 之前 function Person(x, y) { this.x = x this.y = y } let methodsName = 'methodtest' // es6 之后 Class Person { // 类的构造方法 // 一个类只能有一个构造函数 // 1.在内存中创建一个对象 moni = {} // 2.将类的原型prototype赋值给创建出来的对象 moni.__proto__ = Person.prototype // 3.将对象赋值给函数的this: new绑定 this = moni // 4.执行函数体中的代码 // 5.自动返回创建出来的对象 constructor(x, y) { this.x = x this.y = y } // 这些方法都是定义在Person的prototype上面,所以说在类的实例对象上面调用方法,就是在调用原型上面的方法 toString() { return `${this.x},${this.y}` } // 普通的实例方法 // 创建出来的对象进行访问 // var p = new Person() // p.eating() eating() { console.log(this.name + " eating~") } // 可以通过表达式来写方法名称 [methodsName]() { } // 类的访问器方法:可以设置拦截操作 get address() { console.log("拦截访问操作") return this._address } set address(newAddress) { console.log("拦截设置操作") this._address = newAddress } // 静态方法,静态方法有一个static关键词,表示这是一个静态方法,静态方法可以直接在类上面调用,不能在实例上面调用,如果静态方法上存在this,该this指向的是当前类 static staticMethods() { } } // 必须要有这个new var p = new Person(1,2) // Person的类型是一个函数,p对象上的隐式原型和Person上的显示原型是同一个东西 console.log(p.__proto__ === Person.prototype) // true console.log(p) // p { x:1, y:2 }复制代码
es6中,所有同一个类通过new出来的实例对象,都共享同一个原型对象,我们也可以通过实例的_ proto _来进行添加方法
var p1 = new Person(2,3) var p2 = new Person(3,4) p1.__proto__ === p2.__proto__ === Person.prototype // 例如 p1.__proto__.eating = function(){return `${this.name}在吃饭`} // 此时p1和p2都是可以调用该方法的复制代码
class实现继承extends
class Person { constructor(name, age) { this.name = name this.age = age } eating() { console.log(this.name + " eating~") } personMethod() { console.log("处理逻辑1") console.log("处理逻辑2") console.log("处理逻辑3") } } // Student称之为子类,继承字Person类。 class Student extends Person { // JS引擎在解析子类的时候就有要求, 如果我们有实现继承 // 那么子类的构造方法中, 在使用this之前 constructor(name, age, sno) { super(name, age) // 调用父类的constructor(name, age) this.sno = sno } studying() { console.log(this.name + " studying~") } // 类对父类的方法的重写 running() { console.log("student " + this.name + " running") } // 重写personMethod方法 personMethod() { // 复用父类中的处理逻辑 super.personMethod() console.log("处理逻辑4") console.log("处理逻辑5") console.log("处理逻辑6") } } var stu = new Student("xxx", 18, 111) stu.eating() stu.running() stu.personMethod() Student.staticMethod() console.log(Object.getOwnPropertyDescriptors(Person))
作者:陌丶_
链接:https://juejin.cn/post/7019119794720882725