简体   繁体   English

为什么将'this'对象分配给js中的局部变量

[英]Why 'this' object is assigned to a local variable in js

I was going through ext-all-debug.js file from extjs library and most of the class methods had 我正在检查extjs库中的ext-all-debug.js文件,并且大多数类方法都有

var me = this;

How does it helps in performance? 它对性能有何帮助?

It doesn't help in performace but when the function is called in a different scope you still have the pointer to the expected object 它对性能没有帮助,但是当在另一个作用域中调用该函数时,您仍然具有指向预期对象的指针

function someFunc() {
    var me = this;
    someElement.on("click", function() {
        console.log(me);
        console.log(this);
    });
};

when this is logged the console will show the caller of the function. 记录此消息后,控制台将显示该函数的调用方。 In the case where me is logged it will show the element that was clicked on 在我登录的情况下,它将显示单击的元素

It doesn't help with performance. 它对性能没有帮助。 It helps with confusion. 它有助于解决混乱问题。 this gets reassigned a lot, automatically. this会自动重新分配很多。 If you want to remember what this is, you assign it to something else, traditionally me , self or that . 如果您想记住this是什么,可以将其分配给其他东西,传统上是meselfthat Or you use bind . 或者您使用bind It also helps with compression, since me can be compressed to a one-letter variable, but only this is magical and can't be renamed. 它还有助于压缩,因为me可以压缩到一个字母的变量,但仅this是神奇的,不能重命名。

It is not performance related. 它与性能无关。 However by this way it declares a var that can be accessed by other members within this “Closure”. 但是,通过这种方式,它声明了一个var,该“封闭”中的其他成员可以访问该var。 Noted that the "this" of the other members is not determined by the definition context, "this" is whoever calls the function. 注意,其他成员的“ this”不是由定义上下文确定的,“ this”是调用函数的人。 On the contrary, variant scope is always determined by the definition context. 相反,变体范围始终由定义上下文确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM