Class

作者: klmhly | 来源:发表于2019-03-22 20:13 被阅读0次

ES6创建对象的方法,可以看作语法糖,它的本质是函数。让对象原型的写法更清晰,更加像面向对象的语法。

Class与ES5构造函数比较

  • class原型的属性不可枚举,ES5构造函数的原型属性可以枚举
  • class必须使用new调用(否则报错), ES5的构造函数可以以普通函数的形式调用
  • class不存在变量提升,ES5的构造函数存在变量提升。

Class结构

  • constructor(){} 构造函数
  • 原型方法
class Person{
  //构造函数
  constructor(name,age){
    this.name = name
    this.age = age
  }
  
  //原型上方法
  sayName(){
    console.log(this.name)
  }
}

一些特性

  • this
  • 私有方法
  • 私有属性
  • 静态方法/实例方法
  • 静态属性/实例属性
this

类的方法内部如果有this,则默认指向类的实例对象(但如果把方法拿出来单独用,容易报错)

常用以下做法:

  • 在构造函数中为方法绑定this
    this.sayName = this.sayName.bind(this)
  • 使用箭头函数
  • Proxy
私有方法
  1. 在方法名加_
  2. 把方法移到模块外面,然后在构造函数里面绑定this
  3. symbol
class Person {
    constructor(name,friends){
        this.name = name
        this.friends=friends
        sayFriends.call(this,friends)
    }

    //私有方法(第1种写法)
    _sayName(){
        console.log(this.name)
    }
}
// 私有方法(第2种写法)
function sayFriends(friends) {
    this.a= friends
}

私有变量

ES6没有实现私有变量,提案是在属性前面加#

静态方法

是类名直接调用的方法,实例不能调用,在方法前面加static关键字

class Person {
    constructor(name,friends){
        this.name = name
        this.friends=friends
        sayFriends.call(this,friends)
    }

    //静态方法
    static sayHello(){
        console.log('hello')
        console.log(this.name)
    }
}

//调用
Person.sayHello
静态属性

类名.属性名

实例方法

定义在构造函数以及原型上的方法,是给实例调用的方法

实例属性

1)直接在构造函数里面定义的属性
2)用等式写入类的实例中的属性

相关文章

网友评论

    本文标题:Class

    本文链接:https://www.haomeiwen.com/subject/dhervqtx.html