我应该在局部变量中引用'this'吗? [英] Should I reference 'this' in local variable?

查看:75
本文介绍了我应该在局部变量中引用'this'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在代码中看到这一点: var me = this; 。这是为什么?如果我在局部变量中引用'this',会有一些性能上的提升吗?

I often see this in code: var me = this;. Why is that? Is there some performance gain if I reference 'this' in local variable?

推荐答案

如果里面有函数,这很有用一个函数,这些嵌套函数中的代码需要从外部上下文中访问 this 的值。

It's useful if there are functions inside a function, such that code in those nested functions needs access to the value of this from the outer context.

function example() {
  var me = this;
  document.getElementById('whatever').onclick = function() {
    me.clicked = 1;
  };
}

因为这个是为每个函数调用重新建立,而不是在变量中隐藏外部这个,根本无法从内部函数引用它。

Because this is established anew for every function call, without stashing the outer this in a variable there'd be no way to reference it at all from the inner function.

这篇关于我应该在局部变量中引用'this'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆