构造函数

  • 构造函数语法

  • 分析构造函数

  • 构造函数和实例对象的关系

    • 实例的 constructor 属性

    • instanceof 操作符

  • 普通函数调用和构造函数调用的区别

  • 构造函数的返回值

  • 构造函数的问题

  • 更优雅的工厂函数:构造函数

  • 一种更优雅的工厂函数就是下面这样,构造函数:
  • function Person (name, age) {
      this.name = name
      this.age = age
      this.sayName = function () {
        console.log(this.name)
      }
    }
    
    var p1 = new Person('Jack', 18)
    p1.sayName() // => Jack
    
    var p2 = new Person('Mike', 23)
    p2.sayName() // => Mike

    解析构造函数代码的执行

  • 在上面的示例中,Person() 函数取代了 createPerson() 函数,但是实现效果是一样的。这是为什么呢?

    我们注意到,Person() 中的代码与 createPerson() 有以下几点不同之处:

    • 没有显示的创建对象

    • 直接将属性和方法赋给了 this 对象

    • 没有 return 语句

    • 函数名使用的是大写的 Person

    而要创建 Person 实例,则必须使用 new 操作符。以这种方式调用构造函数会经历以下 4 个步骤:

    1. 创建一个新对象

    2. 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象)

    3. 执行构造函数中的代码

    4. 返回新对象

    下面是具体的伪代码:

  • function Person (name, age) {
      // 当使用 new 操作符调用 Person() 的时候,实际上这里会先创建一个对象
      // var instance = {}
      // 然后让内部的 this 指向 instance 对象
      // this = instance
      // 接下来所有针对 this 的操作实际上操作的就是 instance
    
      this.name = name
      this.age = age
      this.sayName = function () {
        console.log(this.name)
      }
    
      // 在函数的结尾处会将 this 返回,也就是 instance
      // return this
    }
原文地址:https://www.cnblogs.com/paoge/p/13837135.html