学微信小程序的时候 看到了:

var that = this 是一种在 JavaScript 中常用的编程技巧,通常用于在不同的函数作用域中保持对当前对象 (this) 的引用。这个技巧主要用于在回调函数或嵌套函数中,确保能够正确访问外部函数的 this 对象。
function OuterFunction() {
this.name = 'Outer';
var that = this; // 保存对外部函数 this 的引用
function InnerFunction() {
console.log(that.name); // 访问外部函数的 this
}
InnerFunction();
}
var obj = new OuterFunction(); // 输出: Outer
在这个例子中,OuterFunction 创建了一个 name 属性,并且定义了一个内部函数 InnerFunction。在调用 InnerFunction 时,直接访问 this.name 会出现问题,因为 this 在 InnerFunction 中引用的是 InnerFunction 自己的上下文,而不是 OuterFunction 的上下文。因此,通过在 OuterFunction 中保存 this 的引用到变量 that,可以在 InnerFunction 中正确访问 OuterFunction 的 name 属性。
这种方法在 ES6 中可以通过箭头函数来简化,箭头函数不会绑定自己的 this,它会捕获其所在的上下文的 this 值。
function OuterFunction() {
this.name = 'Outer';
const InnerFunction = () => {
console.log(this.name); // this 仍然引用 OuterFunction 的 this
}
InnerFunction();
}
var obj = new OuterFunction(); // 输出: Outer
使用箭头函数可以避免显式地保存 this 引用,从而使代码更简洁。
总结:javascript没学好
JavaScript this引用详解
760

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



