构造函数和Class

引出背景

当我们在使用new关键字的时候,我们知道后面接的应该是一个构造函数或者Class类,那么它们之间有什么特性呢?

如果我们要去重写一个Promise(),应该怎么写呢?
平常用promise的时候, 是通过new关键字来new Promise(), 
所以咱们应该用构造函数或者class来实现。

一、构造函数是什么

   function Person(name) {
      this.name = name
      this.sayName = function() {
        console.log(this.name)
      }
    }
    const p1 = new Person('高秀')
    const p2 = new Person('高秀')
    p1.sayName() // 高秀 
    p2.sayName() // 高秀
    console.log(p1.sayName === p2.sayName) //false
    console.log(Person.prototype)
    /*
     * {constructor: ƒ}
     *  constructor: ƒ Person(name)
     *  __proto__: Object
     *  
     * */

由上面的打印结果可以看出,每创建一个实例,就会重新创建一个sayName函数,这样运行起来会消耗一定的性能

二、Class是什么

   class Student {
      constructor(name) {
        this.name = name
      }
      sayName() {
        console.log(this.name)
      }
    }
    const p3 = new Student('麦乐')
    const p4 = new Student('麦乐')
    p3.sayName() // 麦乐
    p4.sayName() // 麦乐
    console.log(p3.sayName === p4.sayName) // true
    console.log(Student.prototype)
    /*
    *{constructor: ƒ, sayName: ƒ}
    constructor: ƒ Student(name),
    sayName: ƒ sayName(),
    __proto__: Object
    */

这里可以看出,类的函数是创建在prototype上的,每个实例的syaName方法都指向同一个地址,也就是说是同一个方法,相对于构造函数来说,性能会有所提高。

联系

相似之处this都指向的是实例。

  function Person(name) {
      this.name = name
      this.sayName = function() {
        console.log(this)
      }
      this.sayHello = function() {
        const check = this.sayName
        check()
      }
    }
    const p1 = new Person('高秀')
    const p2 = new Person('麦乐')
    p1.sayName() // Person {name: "高秀", sayName: ƒ, sayHello: ƒ}
    p2.sayName() // Person {name: "麦乐", sayName: ƒ, sayHello: ƒ}
    p1.sayHello() // undefiend
  class Student {
      constructor(name) {
        this.name = name
      }
      sayName() {
        console.log(this)
      }
      sayHello() {
        const checkThis = this.sayName
        checkThis()
      }
      sayBind() {
        const checkThisBind = this.sayName.bind(this)
        checkThisBind()
      }
    }
    const p5 = new Student('章三')
    const p6 = new Student('历史')
    p5.sayName() // Student {name: "章三"}
    p6.sayName() // Student {name: "历史"}
    p5.sayHello() // undefiend   这里可以解释为什么react中的事件调用函数需要绑定this
    p5.sayBind() // Student {name: "章三"}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值