var that = this

前端项目中经常看到 var that = this - 这句话,作用是什么呢?

stackoverflow 上面找到了一个高分回答 What does 'var that = this;' mean in JavaScript?

Because this frequently changes when you change the scope by calling a new function,
you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.

大概意思是:this对象在程序中的作用域会频繁改变(比如调用一个新的函数),而 var that = this 之后,that不会改变,仍然指向之前的this,这样就不会找不到原来的对象

posted @ 2019-12-04 17:00  snower1995  阅读(196)  评论(0编辑  收藏  举报