es6中的class类

来源:互联网 发布:creis中指数据城市版 编辑:程序博客网 时间:2024/06/05 08:53

constructor是构造方法 this关键字代表着实例对象 定义类的方法不需要加function 直接把函数放进去就可以了,方法直接不需要有逗号,否则会报错

class point {     constructor(x,y){        this.x = x        this.y = y        return this     }     sum(){             return this.x + this.y     }    //构造函数的prototype属性在ES6中继续存在,实际上所有的方法都定义在类的prototype属性上}  var o = new point(1,2).sum()  console.log(o)

类的数据类型就是函数,类本身指向的就是构造函数

    console.log(typeof point) // function    console.log(point === point.prototype.constructor)// true

Object.assign() 可以很方便的向一个类添加很多方法

 class Boll{   constructor(){        this.x = 111   } } Object.assign(Boll.prototype,{     add(){         console.log(1)     },     remove(){         console.log(2)     },     clear(){         console.log(3)     } }) var b = new Boll()

prototype对象的constructor 属性直接指向类本身

 console.log(Boll.prototype.constructor===Boll)  // true

// 类定义内部的所有方法都是不可枚举的

     console.log(Object.keys(point.prototype))     //[] 空数组说明不可枚举    console.log(Object.keys(Boll.prototype))    //['add','remove','clear'] 这三个方法不是在原型里面的         console.log(Object.getOwnPropertyNames(Boll.prototype))

constructor 是类的默认方法,通过new 命令生成对象实例时自动调用该方法,一个类必须有constructor方法,如果没有显示定义会 一个空的constructor会被默认增加
实例对象 生成实例对象 和 es5一样 还是通过new操作符
实例的属性除非显示的定义在其本身上,否则都是定义在原型(即class)上

class xxxx{    constructor(){        this.x = 111           // 实例的属性都定义在 class Boll 这个原型上面,    }}var x = new xxxx()var xx = new xxxx()console.log(x.hasOwnProperty('x'))  // true// 所有的实例共享一个原型对象  x 和 xx 原型都是 xxxxconsole.log(xx.__proto__ == x.__proto__)  // true// name 属性 总是返回紧跟在class关键字后面的类名console.log(xxxx.name)

class 也可以采用表达式的形式定义

 const myClass = class me {     getClassName(){         return me.name     }     // 上面的代码用表达式的形式定义了一个类 这个类名为myClass 而不是me ,me只有在内部才可用,指代当前类}let inst = new myClass()console.log(inst.getClassName())// console.log(me.name) 报错了// 如果class内部没有用到me 可以省略// 另外class不存在变量提升, 如果先 创建实例在定义类 会报错,所以在定义类是 必须保证子类在父类之后定义 
原创粉丝点击