ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ****** ## 1 Class的意义 1. js语言传统方法通过构造函数,定义生成新对象, ~~~ function Point(x,y){ this.x = x; this.y = y; } Point.prototype.toString = function () { return '(' + this.x + ', ' + this.y + ')'; } ~~~ 2. ES6提供了Class语法糖,来简化对象的创建。通过Class关键字,可以定义类。 ~~~ //定义类 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } ~~~ 3. ES6的类,完全可以看做构造函数的另一种写法 ~~~ ;类的数据类型是函数,类本身指向构造函数 class Point{ // ... } typeof Point // "function" Point === Point.prototype.constructor // true ;构造函数的prototype属性,在ES6的类上面继续存在。类的所有方法都定义在类的prototype属性上面 class Point { constructor(){ // ... } toString(){ // ... } toValue(){ // ... } } // 等同于 Point.prototype = { toString(){}, toValue(){} } ;在类的实例上调用方法,其实就是调用原型上的方法 class B {} let b = new B(); b.constructor === B.prototype.constructor // true ;类的方法都定义在prototype属性上面,类的新方法可以添加在prototype上面。Object.assign可以很方便一次向类添加多个方法,而prototype对象的constructor属性,直接指向类的本身。类的内部定义的所有方法,都是不可枚举的,这一点与ES5的行为不一致。 ~~~ class Point { constructor(){ // ... } } Object.assign(Point.prototype, { toString(){}, toValue(){} }) Point.prototype.constructor === Point // true class Point { constructor(x, y) { // ... } toString() { // ... } } Object.keys(Point.prototype) // [] Object.getOwnPropertyNames(Point.prototype) // ["constructor","toString"] ~~~ ## 2 constructor方法 1. constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法,一个类必须有constructor方法,没有显示定义,空的constructor方法会被默认添加 ## 3 创建实例对象 ## 4 Class的继承 ## 5