Accessing variables of parent function in Javascript event handlers

夙愿已清 提交于 2019-12-11 17:15:42

问题


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?

来源:https://stackoverflow.com/questions/6490778/accessing-variables-of-parent-function-in-javascript-event-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!