有关this的三种指向问题

144 阅读1分钟

2020-4-25 晚
干完饭,打开电脑,不知怎的,就想起了这些. 当时那些困扰我的问题,你们曾经有吗?

构造函数new的工作原理

  1. 创建对象

  2. this指向这个对象

  3. 给对象赋值

  4. 返回这个对象

function Person(name, age, sex) {
            //(1)创建空对象  {}
            //(2)将this指向这个对象  this = {}
            //(3)对象赋值
            this.name = name
            this.age = age
            this.sex = sex
            //(4)返回这个对象  return this
        }

        let person = new Person('小明', 20, '男')
        console.log(person)

函数中this的三种指向

  1. 普通函数: 函数名() this指向window
  2. 构造函数: new 函数名() this指向new创建的实例
  3. 对象方法: 对象名.方法名() this指向对象

一句话小结:没点 '. ',没有new this指向window,有new指向实例.有点指的的是'.'左边的对象.