1、没有指定call的指向,此时 aObjFun 里的 this 指向它自己,并且获取不到 data 的值。
const _this = this;
const data = 6;
const aObj = {
aObjFun(test1, test2) {
const a_this = this;
if (this.data) console.log(this.data);
return {a_this, test1, test2}
}
}
console.log(aObj.aObjFun.call('1','2'))
// {a_this: String {'1'}, test1: '2', test2: undefined}
2、给call第一个参数传入最外层的 this 参数时,aObjFun 的指向则跟最外层 this 的指向一致,同时也能获取到 data 的值了。
console.log(aObj.aObjFun.call(_this,'1','2'))
// {a_this: Window, test1: '1', test2: '2'}
文章讨论了JavaScript中对象方法`aObjFun`的this指向问题,当没有明确call的指向时,this指向自身且无法访问data。通过call方法传递外部this参数,可以改变`aObjFun`的指向并获取到data值。
2376

被折叠的 条评论
为什么被折叠?



