this 作用域指向详解
-
this总是代表着他的直接调用者,例如obj.fun(),那么fun()中的this就是obj
举例
import axios from 'axios' export default new class { constructor() { this.sayhello() // => "hello" axios.get('xxx.com').then(function() { // 此时this指向的是function函数本身,无法获取到父级的方法 this.sayhello() // => sayhello undefined }) // 箭头函数修改this作用域 axios.get('xxx.com').then(() => { this.sayhello() // => "hello" }) // 拷贝this作用域 var that = this axios.get('xxx.com').then(function() { that.sayhello() // => "hello" }) } sayhello() { console.log('hello') } }