Javascript “发送的最佳方式”;这";对象到回调函数

Javascript “发送的最佳方式”;这";对象到回调函数,javascript,jquery,performance,Javascript,Jquery,Performance,最近我的很多代码都是这样的 function MyObjectClass (selector) { this.color = "red"; this.$elt = $(selector); // ... any other object vars here ... // Example method for the object this.showThenUpdateColor = function () { // Keep a

最近我的很多代码都是这样的

function MyObjectClass (selector) {
    this.color  = "red";
    this.$elt   = $(selector);
    // ... any other object vars here ...

    // Example method for the object
    this.showThenUpdateColor = function () { 
        // Keep a copy of "this" to use for callbacks
        var o = this;
        // Example of jQuery function that accepts a callback           
        o.$elt.fadeIn(function(){ 
            // Inside of this callback function we need to access the main object
            o.$elt.css({
                "background-color" : o.color // This is where we need the "o"
            });
        });
    }
}
var myObject = new MyObjectClass('#myObject');
myObject.showThenUpdateColor();
…在对象方法内部有一个回调。通常,我将对象本身(“this”)分配给一个局部变量(通常为“o”,因为它很短且简单),可以在回调中使用


这是内存的最佳使用吗?有内存泄漏的危险吗?有更好的方法吗?

我建议您看看。它允许您创建一个函数,该函数在执行时在指定的范围内执行另一个函数。然后你可以写:

this.showThenUpdateColor = function () { 
    // Example of jQuery function that accepts a callback           
    this.$elt.fadeIn($.proxy(this._onFadeInComplete, this));
}

function _onFadeInComplete() {
    this.$elt.css({
        "background-color" : this.color
    });
}

我只是将这个链接[1]添加到讨论中,这很有趣。答案(不仅是公认的答案)很好地解释了如何处理“这一问题”。无论如何,你的问题是不同的:“这是对记忆的最佳利用吗?”。这就是我在评论中提供这一点的原因,我将关注讨论。[1] 是的,不是,也不是——只有其他的方法。谢谢你,伯吉,这是我想要的基本答案。虽然理想的答案应该包括一些解释,说明我们如何知道这是对记忆的最佳利用。当我设置
var o=this时它只是创建了一个对对象的引用,我假设这个对象在内存中非常小?也不确定闭包是否有一些内存含义?使用
函数\u onFadeInComplete
而不是
这个函数的好处是。\u onFadeInComplete=function()。