JS&ES6的this指向问题
普通函数
- 普通函数this——用于访问当前方法所属的对象
- 普通函数的this跟定义无关,跟调用有关
let obj = {
a: 12,
fn() {
consolse.log(this == obj)
}
}
obj.fn()
let obj = {
a: 12,
}
obj.fn = function() {
console.log(this == obj)
}
obj.fn()
document.onclick = function() {
consolse.log(this == doucument)
}
------------------------------------------------------------------------------
function show() {
console.log(this)
}
show();
let arr=[1, 2, 3]
arr.fn = show
arr.fn()
setTimeout(show, 100)
new show()
show.call(11)
show.call('sssd')
show.call({a: 12})
arr.forEach(function() {
console.log(this, item)
})
arr.forEach(function() {
console.log(this, item)
}, "强制改变的this")
箭头函数
- 普通函数——function this取决于调用,this不固定
- 箭头函数—— => this取决于定义,定义完成则不会改变,取决于定义时当前环境的this
let obj = {
a: 12,
() => {
consolse.log(this == obj)
}
}
obj.fn()