Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
引用对象方法时,是否应将其存储在变量中?(JavaScript)_Javascript_Oop_Variables_This - Fatal编程技术网

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

引用对象方法时,是否应将其存储在变量中?(JavaScript),javascript,oop,variables,this,Javascript,Oop,Variables,This,其中,我使用this多次引用JavaScript对象 var myObj = { method1 : function() {}, method2 : function() {}, method3 : function {}, init : function() { this.method1(); this.method2(); this.method3(); } }; 是否存在任何类型的性能增益?我是否应该将此存储

其中,我使用
this
多次引用JavaScript对象

var myObj = {
   method1 : function() {},
   method2 : function() {},
   method3 : function {},
   init : function() {
       this.method1();
       this.method2(); 
       this.method3();  
   }
};
是否存在任何类型的性能增益?我是否应该将此
存储在变量中?比如:

init : function() {
    var self = this;

    self.method1();
    self.method2(); 
    self.method3();  
}

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

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

init : function() {

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

}

在你的例子中,你不需要创建一个局部变量,并在你真的不需要的时候给它赋值。它是多余的,而且还创建了一个不需要的变量。

您显然误解了使用
self
+1来回答一个写得很好的问题。谢谢您的回答!如果我多次调用对象的属性,比如多次调用“this.property1.something”,或者我应该将它们存储在变量中,那么同样的情况是否成立呢?
this.property1.something
可以从分配给局部变量中获益,如果,
。something
是以昂贵的方式从dom中计算出来的。另外,如果您将执行一系列操作,并且只需要“持久化”结果(同样,最有可能是dom Related。)@Andrew-这是一个非常好的观点!谢谢你指出这一点。