JS 总结之 class

class 是 ES6 的新特性,能够用来定义一个类,实际上,class 只是一种语法糖,它是构造函数的另外一种写法。(什么是语法糖?是一种为避免编码出错和提升效率编码而生的语法层面的优雅解决方案,简单说就是,一种便携写法。)es6

class Person {

}
typeof Person // "function"
Person.prototype.constructor === Person // true
复制代码

🚗 使用

用法和使用构造函数同样,经过 new 来生成对象实例函数

class Person {

}
let jon = new Person()
复制代码

🚌 constructor

每一个类都必需要有一个 constructor,若是没有显示声明,js 引擎会自动给它添加一个空的构造函数:ui

class Person {

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

  }
}
复制代码

🏎 属性和方法

定义于 constructor 内的属性和方法,即定义在 this 上,属于实例属性和方法,不然属于原型属性和方法。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
复制代码

静态方法能够被子类继承spa

// ...
class Sub extends Person {

}
Sub.doSay() // hello
复制代码

能够经过 super 对象访问prototype

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

🚜 严格模式

不须要使用 use strict,由于只要代码写在类和模块内,就只能使用严格模式。code

🏍 提高

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
复制代码

🚀 参考

相关文章
相关标签/搜索