this指向共分为4个关键点:
常见this,new 实例化this,箭头函数,apply、bind、call
1. 常见this
归根结底一句话,谁最终调用函数,this指向谁!!,下面直接看例子
var name = 'Bill';var person = {name: 'Alice',sayName: function () {console.log(this.name)}}person.sayName(); // Alice----------------------------------var name = 'Bob',person = {name: 'Alice',sayName: function () {console.log(this === person); // truereturn function () {console.log(this === person); // falseconsole.log(this === window); // trueconsole.log(this.name); // Bob}}}person.sayName()();// 可以看作先调用person.sayName() 则指向person// 再调用函数fn(),因为在外部调用则this指向window----------------------------------var name = 'boss';var boss1 = {name: 'boss1',returnThis () {return this}}var boss2 = {name: 'boss2',returnThis () {return boss1.returnThis()}}var boss3 = {name: 'boss3',returnThis () {var returnThis = boss1.returnThisreturn returnThis()}}boss1.returnThis() // this指向 boss1boss2.returnThis() // this指向 boss1boss3.returnThis() // this指向 window
2. new实例化的this指向
// 只指向实例化的对象var name = 'Bob';function Person(name) {this.name = name;return this;}var person1 = new Person('Alice');console.log(person1.name); // Alice----------------------------------var name = 'Bob';function Person(name) {this.name = name;return {name: 'LiLei'};}var person1 = new Person('Alice');console.log(person1.name); // LiLei// 如果在构造器中返回一个指定对象则this指向返回的对象
3. 箭头函数中this指向
// 箭头函数主要看在哪里被创建// 箭头函数的this指向是不会被call apply bind改变的function callback (cb) {cb()}callback(() => { console.log(this) }) // windowvar boss1 = {name: 'boss1',callback: callback,callback2 () {callback(() => { console.log(this) })}}boss1.callback(() => { console.log(this) }) // boss1boss1.callback2() // boss1-----------------------------------var returnThis = () => thisreturnThis() // windowvar boss1 = {name: 'boss1',returnThis () {var func = () => thisreturn func()}}returnThis.call(boss1) // window 因为箭头函数不会被改变var boss1returnThis = returnThis.bind(boss1)boss1returnThis() // window 因为箭头函数不会被改变boss1.returnThis() // boss1 因为箭头函数是啊在boss1中被定义 拿去上下文thisvar boss2 = {name: 'boss2',returnThis: boss1.returnThis}boss2.returnThis()/***可以改写为如下 同等***/var boss2 = {name: 'boss2',returnThis: func = () => this}boss2.returnThis() // boss2
4. apply,call,bind 决定this指向
// 他们三个第一个参数都可以改变this的指向// bind返回的是一个新的函数表达式,call,apply是函数的调用// apply跟call比 第二个参数不一样 apply接收的是一个数组
