Accessing variables of parent function in Javascri

2019-09-09 20:56发布

问题:

I have an event handler which is bound to a 'change' event. The problem is, functions within that function cannot access any elements of the parent function

Process.prototype.handleCheckboxChange = function(event) {
    var rgbs = []
    $(':checked').each(function(index,element) {
       var color = [0,3,4];
       rgbs.push(color);
    })
}

I have been reading all around the place about closures, but everything I have seen seems to indicate that an inner function should be able to access its parents local variables, whereas this is not the case here: rgbs is undefined.

It may be of use to know that when binding (with jQuery's bind()) I am using closures to set the this keyword to the original object (in a way I don't really understand), although the problem was the same when I was not doing this:

Process.prototype.doBinding = function() {
   $('checkbox').bind('change', function(event) {self.handleCheckboxChange(event)})
}

Any ideas on what I am doing wrong and how I can access rgbs?