var that=this

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

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 会出现问题,因为 thisInnerFunction 中引用的是 InnerFunction 自己的上下文,而不是 OuterFunction 的上下文。因此,通过在 OuterFunction 中保存 this 的引用到变量 that,可以在 InnerFunction 中正确访问 OuterFunctionname 属性。

这种方法在 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没学好

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值