Trouble With JS Closure
I have this js:
(function () {
Namespace = {
settings: {
myVar: 'test'
},
init: functio开发者_C百科n() {
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
this.someOtherFunction(); // doesn't work
console.log(this.settings.myVar); // doesn't work
}
},
someOtherFunction: function() {
console.log('test');
}
}
Namespace.init();
})();
I'm losing the context of 'this' when I go into my onSubmit function. Can you help me understand why this is happening and how to work around this situation?
Try the this that trick.
Before you closure set a variable called 'that' to this.
var that = this;
Then use that in you closure. The problem you have having is that the closure is attached to you DOM node and not your object. So when you closure was called this had the value of the DOM node.
Inside memberSearchFrm.onsubmit
, this
refers to memberSearchFrm
, not to the object you want. You need to save a reference to this
.
init: function() {
var that = this;
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
that.someOtherFunction();
console.log(that.settings.myVar);
}
},
I ran into this same issue with closures and made this fiddle to experiment with different ways to call other functions in a closure.
http://jsfiddle.net/7FzEz/5/
I finally settled with this format:
(function () {
var obj = {
settings: {
myVar: 'test'
},
init: function() {
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
obj.someOtherFunction();
console.log(obj.settings.myVar);
}
},
someOtherFunction: function() {
console.log('test');
}
}
obj.init();
})();
精彩评论