Javascript 在jQuery回调中访问父属性

Javascript 在jQuery回调中访问父属性,javascript,jquery,Javascript,Jquery,不确定我的措辞是否正确,但在回调中如何引用基类的controls属性 这一直困扰着我一段时间,我通常都会解决它,但如果有人能告诉我应该如何正确地做到这一点,我将不胜感激 var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) {

不确定我的措辞是否正确,但在回调中如何引用基类的controls属性

这一直困扰着我一段时间,我通常都会解决它,但如果有人能告诉我应该如何正确地做到这一点,我将不胜感激

var base = function() {
    var controls = {};

    return {
        init: function(c) {
            this.controls = c
        },
        foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).change(function() {
                $(this.controls.PlaceHolder).toggle();
            });
        }
    }
};
非常感谢


Paul

您需要在这里利用闭包

var base = function() {
var controls = {};

return {
    init: function(c) {
            this.controls = c
    },
    foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).change(function(controls) {
                    return function(){
                        $(controls.PlaceHolder).toggle();
                    }
            }(this.controls));
    }
}

})

使用闭包的威力:

var base = function() {
    var controls = {};

    return {
        init: function(c) {
                this.controls = c
        },
        foo: function(args) {
                var self = this;

                this.init(args.controls);
                $(this.controls.DropDown).change(function() {
                        $(self.controls.PlaceHolder).toggle();
                });
        }
    }
};
虽然是,但也可以使用jquery
bind
传递对象:

var base = function() {
    var controls = {};

    return {
        init: function(c) {
            this.controls = c
        },
        foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).bind('change', {controls: this.controls}, function(event) {
                $(event.data.controls.PlaceHolder).toggle();
            });
        }
    }
};

用更优雅的解决方案来击败我:当我使用这种方法时,有些奇怪的事情似乎正在发生。单击事件在页面加载时触发。我认为这与回调函数中的controls参数有关,因为当我删除它时,click事件不会自动触发。我喜欢这种方法,我想如果我在代码中广泛使用jQuery,我应该使用bind方法。我可能只是使用闭包一段时间,这样我就习惯了使用闭包,一旦熟悉了,我就可以使用闭包。谢谢