前言
本文首发于笔者的个人博客,欢迎围观。
如果在阅读过程发现文章有表达不当的地方,希望不吝指教。
本章通过代码案例,简化this
的使用情况。通过阅读文章,掌握this
在不同情况下的指向。
图解
接下来将围绕这这张图片展开讲解。
普通函数
谁调用了函数,谁就是
this
.
eg:
function foo() {
console.log(this.a)
}
var a = 1
foo()
const obj = {
a: 2,
foo
}
obj.foo()
const c = new foo()
复制代码
- 直接调用
foo
,不管foo
放在哪里,this
一定是window
. obj.foo()
,obj
调用了函数,所以this
就是obj
对象。- 对于
new
来说,this
被永远绑定在c
上面,不会被任何方式改变this
.
箭头函数中的this
箭头函数的
this
不适用其他规则,而是根据外层(函数或者全局)上下文来决定。
eg:
const foo = {
fn: function() {
setTimeout(() => {
console.log(this)
})
}
}
console.log(foo.fn())
// {fn: f}
复制代码
箭头函数是没有this
的,箭头函数中的this
只取决包裹箭头函数的第一个普通函数的this
. 另外箭头函数使用bind
这类函数是无效的。
bind/call/apply
apply
,call
,bind
都是可以修改this
指向的。
eg:
var a = {
name : "Cherry",
func1: function () {
console.log(this.name)
},
func2: function () {
setTimeout( function () {
this.func1()
}.bind(a)(),100);
}
};
a.func2() // Cherry
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END