JS 中的 this 指向问题
JavaScript
中this
指向是可以改变的, this
默认指向函数外的对象。
下面info
函数中的this
默认指向 zs
对象。
let zs = {
name: "张三",
age: 12,
info: function() {
console.log(this.name + "今年" + this.age + "岁了!")
}
}
zs.info()
// 张三今年12岁了!
下面是通过call
函数改变了 info
中的 this
的指向,由zs
对象变为ls
对象。
let zs = {
name: "张三",
age: 12,
info: function() {
console.log(this.name + "今年" + this.age + "岁了!")
}
}
let ls = {
name: "李四",
age: 18
}
zs.info.call(ls)
// 李四今年18岁了!
通过调用 call
函数我们就改变了 info
中的 this
指向,其实可以改变 this
指向的函数不止 call
,还有 apply
和 bind
。
// apply
zs.info.apply(ls)
// bind
zs.info.bind(ls)()
Tips:ES6
中的箭头函数是不可以改变 this 指向的,箭头函数的 this
永远指向外部函数的 this
。
let zs = {
name: "张三",
age: 12,
info: function () {
return () => {
console.log(this.name + "今年" + this.age + "岁了!")
}
}
}
let ls = {
name: "李四",
age: 18
}
//zs.info()返回箭头函数再调用call函数
zs.info().call(ls)
// 张三今年12岁了!
此时箭头函数指向为外部函数 this
指向,我们改变外部函数 this
指向后再看下箭头函数的 this
指向。
// 先改变info函数的指向再调用箭头函数
zs.info.call(ls)()
// 李四今年18岁了!
我们发现外部函数调用 call
后箭头函数的 this
指向也变了。
End