构造函数和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 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: "章三"}

猜你喜欢

转载自blog.csdn.net/qq_41831345/article/details/92830833
今日推荐