匿名函数
匿名函数的this
指向调用者
改变this
指向的方法有
-
call()
:第一个参数为函数上下文的对象,后面为函数参数列表-非数组 -
apply()
:第一个参数为函数上下文的对象,第二个参数为函数参数组成的数组 -
bind()
:第一个参数为函数上下文的对象,后面为函数参数列表-非数组,不会立即执行
var fn = function () {
console.log('普通匿名函数', this) // 指向window
}
var person = {
name: 'Chen',
getName: function () {
console.log('对象匿名函数', this) // 指向person
return this.name
},
getThis: function () {
return function () {
console.log('内部匿名函数', this) // 指向window
}
}
}
person.getName()
person.getThis()()
箭头函数
箭头函数没有prototype
,所以本身没有this
。箭头函数内部this
指向外层第一个普通函数的this
var fn = () => {
console.log('箭头函数')
}
网友评论