2020-4-25 晚
干完饭,打开电脑,不知怎的,就想起了这些. 当时那些困扰我的问题,你们曾经有吗?
构造函数new的工作原理
-
创建对象
-
this指向这个对象
-
给对象赋值
-
返回这个对象
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的三种指向
- 普通函数: 函数名() this指向window
- 构造函数: new 函数名() this指向new创建的实例
- 对象方法: 对象名.方法名() this指向对象
一句话小结:没点 '. ',没有new this指向window,有new指向实例.有点指的的是'.'左边的对象.