JavaScript中new一个对象发生了什么

使用new操作符,创建Person的实例:

   function Person(name, age, gender) {
      this.name = name
      this.age = age
      this.gender = gender
      // this.do = function () {
      //   console.log('干活')
      // }
      Person.prototype.do = function () {
        console.log('干活')
      }
    }
    var zs = new Person('zs', 18, '男')
    zs.do()


    class Person {
      constructor() {
        this.name = name
        this.age = age
        this.gender = gender
      }
      do() {
        console.log('干活')
      }
    }
    var zs = new Person('zs', 18, '男')
    zs.do()

1.创建了一个新对象zs

2.给对象设置__proto__,值为构造函数对象的prototype值(this指向了这个对象)

this.__proto__=Fn.prototype

3.执行构造函数中的代码(给这个新对象添加属性和方法)

4.返回新对象

猜你喜欢

转载自blog.csdn.net/weixin_70443954/article/details/128173346