JS 总结之class

《JS 总结之class》

class 是 ES6 的新特征,能够用来定义一个类,实际上,class 只是一种语法糖,它是组织函数的另一种写法。(什么是语法糖?是一种为防止编码失足和进步效力编码而生的语法层面的文雅解决方案,简单说就是,一种便携写法。)

class Person {

}
typeof Person // "function"
Person.prototype.constructor === Person // true

🚗 运用

用法和运用组织函数一样,经由过程 new 来生成对象实例

class Person {

}
let jon = new Person()

🚌 constructor

每一个类都必须要有一个 constructor,假如没有显现声明,js 引擎会自动给它增加一个空的组织函数:

class Person {

}
// 等同于
class Person {
  constructor () {

  }
}

🏎 实例属性和要领,原型属性和要领

定义于 constructor 内的属性和要领,即定义在 this 上,属于实例属性和要领,不然属于原型属性和要领。

class Person {
  constructor (name) {
    this.name = name
  }

  say () {
    console.log('hello')
  }
}

let jon = new Person()

jon.hasOwnPrototype('name') // true
jon.hasOwnPrototype('say') // false

🚓 属性表达式

let methodName = 'say'
class Person {
  constructor (name) {
    this.name = name
  }

  [methodName] () {
    console.log('hello')
  }
}

🚚 静态要领

不须要经由过程实例对象,能够直接经由过程类来挪用的要领,个中的 this 指向类自身

class Person {
  static doSay () {
    this.say()
  }
  static say () {
    console.log('hello')
  }
}
Person.doSay() // hello

静态要领能够被子类继续

// ...
class Sub extends Person {

}
Sub.doSay() // hello

能够经由过程 super 对象接见

// ...
class Sub extends Person {
  static nice () {
    return super.doSay()
  }
}
Sub.nice() // hello

🚜 严厉形式

不须要运用 use strict,由于只需代码写在类和模块内,就只能运用严厉形式。

🏍 提拔

class 不存在变量提拔。

new Person() // Uncaught ReferenceError: Person is not defined
class Person {

}

🚄 name 属性

name 属性返回了类的名字,即紧跟在 class 背面的名字。

class Person {

}
Person.name // Person

🚈 this

默许指向类的实例。

🚂 取值函数(getter)和存值函数(setter)

class Person {
  get name () {
    return 'getter'
  }
  set name(val) {
    console.log('setter' + val)
  }
}

let jon = new Person()
jon.name = 'jon' // setter jon
jon.name // getter

🛥 class 表达式

假如须要,可为类定义一个类内部名字,假如不须要,能够省略:

// 须要在类内部运用类名
const Person = class Obj {
  getClassName () {
    return Obj.name
  }
}
// 不须要
const Person = class {}

马上实行的 Class:

let jon = new class {
  constructor(name) {
    this.name = name
  }
  sayName() {
    console.log(this.name)
  }
}('jon')

jon.sayName() //jon

🚀 参考

    原文作者:Karon_
    原文地址: https://segmentfault.com/a/1190000017484100
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞