构造函数new的原理

216 阅读1分钟

作用:创建多个对象,但是使代码更简洁

new关键字的原理:

  1. 创建空对象 {}
  2. this指向这个对象 this = {}
  3. 对象赋值 this.name = name
  4. 返回这个对象 return this
    //需求: 创建多个对象 (姓名、性别、年龄)
    function Person(name,sex,age){
    this.name = name
    this.age = age
    this.sex = sex
    }
    
    let p1 = new Person('王富贵','男',18)
    let p2 = new Person('王小二','男',28)
    let p3 = new Person('王二狗','女',39)
    console.log(p1)
    console.log(p2)
    console.log(p3)
    

运行结果:

Snipaste_2022-04-18_21-40-48.png

注意 : 构造函数内部使用return

  • return 基本数据类型的值 无效,返回new创建的对象
  • return 复杂数据类型的值 有效,覆盖new创建的对象