在引用对象方法时,是否应该将其存储在变量中?(JavaScript)

Should this be stored in a variable when referencing to an objects methods? (JavaScript)

本文关键字:变量 存储 JavaScript 方法 对象 引用 是否      更新时间:2023-09-26

我使用 this 多次引用 JavaScript 对象

var myObj = {
   method1 : function() {},
   method2 : function() {},
   method3 : function {},
   init : function() {
       this.method1();
       this.method2(); 
       this.method3();  
   }
};

是否有任何类型的性能提升,我是否应该将this存储在变量中?喜欢:

init : function() {
    var self = this;
    self.method1();
    self.method2(); 
    self.method3();  
}
无需将

this引用存储在变量中,除非您需要将该上下文传递到闭包中。

下面是一个示例,说明

何时可能需要将this指针传递到闭包中,例如元素上的单击事件,该元素需要引用this指针在事件的外部父上下文中指向的任何内容:

init : function() {
    $('.someElem').click( 
        (function(self) {
            return function() {
                self.method1();
                self.method2(); 
                self.method3();  
            }
        })(this)   // pass "this" into the "self" parameter as an argument
    );
}

在您的情况下,您不必要地创建一个局部变量,并在您真的不需要时为其分配一些东西。它是多余的,并且还会创建一个不需要的变量。