改变 this 的指向的方法总结如下:
- 使用 ES6 的箭头函数:箭头函数的 this 始终指向函数定义时的 this,而非执行时。
- 在函数内部使用
_this = this - 使用
apply、call、bind - new 实例化一个对象
1、箭头函数中this指向创建它时外层的this,不可与new一起用,其this指向不会被修改
func = () => { console.log('箭头函数'); }
func()
new func()
2、new关键字调用函数时,一定是指向JS创建的新对象
3、bind只认第一次修改,不能修改箭头函数的this指向,优先级低于new
function test1(){
console.log(this);
}
test1()
test1.bind(1).bind(2)()
function func() {
console.log(this, this.__proto__ === func.prototype)
}
boundFunc = func.bind(1)
boundFunc() // 1 false
new boundFunc() // Object true,new 优先
4、apply 和 call,优先级低于箭头函数和bind apply() 和 call() 的第一个参数都是 this,区别在于通过 apply 调用时实参是放到数组中的,而通过 call 调用时实参是逗号分隔的。
function test2() { console.log(this); }
test2.call([1, 2])
test2()
5、对象调用则指向对象
6、在函数不满足前面的场景,被直接调用时,this 将指向全局对象。在浏览器环境中全局对象是 Window,在 Node.js 环境中是 Global。
7、不在函数里
在 <script /> 标签里,this 指向 Window。
在 Node.js 的模块文件里,this 指向 Module 的默认导出对象,也就是 module.exports。
8、在非严格模式下,如果得出 this 指向是 undefined 或 null,那么 this 会指向全局对象。在浏览器环境中全局对象是 Window,在 Node.js 环境中是 Global。