Javascript:从给定的两个片段中引用“this”的可接受方式

Javascript: Acceptable way to referencing `this` from given two snippets

本文关键字:this 引用 接受方 可接受 片段 Javascript 两个      更新时间:2023-09-26
var me = null;
var testFn = (function() {
    me = this;
    return {
        me1: me,
        fn1 : function() {
           me = this;
             return {   
                    me2 : me,
                    fn2 : function() {
                        me = this;
                        return {
                            me3: me
                        }
                    }
                }        
        }
    }
})();

或:

var testFn = (function() {
    var me = this;
    return {
        me1: me,
        fn1 : function() {
           var me = this;
             return {   
                    me2 : me,
                    fn2 : function() {
                        var me = this;
                        return {
                            me3: me
                        }
                    }
                }        
        }
    }
})();

在上面给出的两个段之间,哪一个是引用this的最佳方式。还有其他最好的方法吗,请建议。

谢谢。。。。。

我建议使用第二种方法,因为我是在闭包中声明的,因此 iot 不会在不需要的地方污染上下文。我也更清楚我属于哪个背景。

我更喜欢第二个,因为它在this时被破坏,这更有意义(它们在同一个范围内)。

不完全相关,但大多数人称变量为that:例如 var that = this;