$.proxy()没有按预期工作.我怀疑它对嵌套对象不起作用

$.proxy() is not working as expected. I suspect it doesn't work on nested object

本文关键字:怀疑 嵌套 不起作用 对象 工作 proxy      更新时间:2023-09-26

我第一次了解这个函数是通过阅读bootstrap.js源代码。如果你不熟悉,这是文件。

通过多次试验&错误,我发现$.proxy()不适用于多层对象。这是真的吗?下面是我的代码:

ProgressBtn.prototype.reset = function(ms) {
        var self = this;
            //this.$progressInicator is a jquery object
        // here is the problem: reset() call is not working, nor displaying error
            var reset = $.proxy( this.$progressIndicator.css, 
                        this, 
                        {'background-color': 'red'}
            );          
            reset();
        console.log('reset is running');
}

我认为这行代码有问题:

var reset = $.proxy( this.$progressIndicator.css, 
                     this, 
                     {'background-color': 'red'}
            );

你能帮我诊断这个问题吗?谢谢!

问题是你有这个:

var reset = $.proxy( this.$progressIndicator.css, 
    this, 
    {'background-color': 'red'}
);

这基本上会导致这种情况发生:

this.$progressIndicator.css.call(this, {'background-color': 'red'});

但是this不是一个jQuery对象,用这个上下文调用css将不起作用。

你需要这个:

var reset = $.proxy( this.$progressIndicator.css, 
    this.$progressIndicator, 
    {'background-color': 'red'}
);

然而,我不明白为什么你这样做,如果你想要你的reset方法做的唯一的事情是改变一个对象的CSS属性。您可以使用以下命令实现相同的目的:

ProgressBtn.prototype.reset = function(ms) {
    this.$progressIndicator.css({'background-color': 'red'});
};

$.proxy是有用的,当你想要附加一个处理程序到一个事件,并希望该处理程序执行与特定的上下文(如。net委托)