普通函数:this指向调用它的对象,箭头函数:this指向定义它的上下文的this指向
var name = 'window'
var person1 = { name: 'person1', show1: function () { console.log(this.name) }, show2: () => console.log(this.name), show3: function () { return function () { console.log(this.name) } }, show4: function () { console.log(this.name, 2222) return () => console.log(this.name) } }
var person2 = { name: 'person2' }
person1.show1() // person1 person1.show1.call(person2) // person2 person1.show2() // window person1.show2.call(person2) // window person1.show3()() // window person1.show3().call(person2) // person2 person1.show3.call(person2)() // window person1.show4()() // person12222 person1
可以看到两个this指向是一致的
person1.show4().call(person2) // person12222 person1
person1.show4.call(person2)() // person2222 person2
构造函数的过程:
1,创建新对象
2,将构造函数的作用域赋给新对象(this指向了新对象)
3,执行构造函数代码(为这个新对象添加属性)
4,返回新对象
一个箭头函数表达式的语法比一个函数表达式更短,并且不绑定自己的 this,arguments,super或 new.target。...箭头函数会捕获其所在上下文的 this 值,作为自己的 this 值。
也就是说,普通情况下,this指向调用函数时的对象。在全局执行时,则是全局对象。
箭头函数的this,因为没有自身的this,所以this只能根据作用域链往上层查找,直到找到一个绑定了this的函数作用域(即最靠近箭头函数的普通函数作用域,或者全局环境),并指向调用该普通函数的对象。
或者从现象来描述的话,即箭头函数的this指向声明函数时,最靠近箭头函数的普通函数的this。但这个this也会因为调用该普通函数时环境的不同而发生变化。导致这个现象的原因是这个普通函数会产生一个闭包,将它的变量对象保存在箭头函数的作用域中
var name = 'window'
function Person (name) {
console.log(this, 222)
this.name = name; this.show1 = function () { console.log(this.name) } this.show2 = () => console.log(this.name) this.show3 = function () { return function () { console.log(this.name) } } this.show4 = function () { console.log(this.name, 2222) return () => console.log(this.name) } }
var personA = new Person('personA')
var personB = new Person('personB')
personA.show1() // personA personA.show1.call(personB) // personB
personA.show2() // Person:{name: “personA”} personA
personA.show2.call(personB) // personA personA.show3()() // window personA.show3().call(personB) // personB personA.show3.call(personB)() // window personA.show4()() // personA2222 personA personA.show4().call(personB) // personA2222 personA personA.show4.call(personB)() // personB2222 personB