Javascript Closure technique
- I have an object which creates a slideshow.
- I want to have several slideshows on a page
- I have an event handler for slideshow element inside it
- I want the event handler to know which slideshow object has created an item clicked
-
slideshow=function(){
var g = document.createElement(...);
...
g.onclick = f1;
f1 = function(slideshow_instance, event) {
//EXPLAIN ME HOW TO GET THE slideshow_instance
}
}
var sl1 = new slideshow();
var sl2 = new slideshow();
Clicking on an element slideshow has created shoul开发者_运维百科d return either
sl1
or
sl2
I explain well?
Short answer, use: this
.
Longer answer, what you want is:
slideshow=function(){
/* ... */
var self = this;
f1 = function(event) {
// do stuff with self.
}
}
The reason you need to point to this
using self
is that event handlers will change the meaning of this
when they are called. But at the time the object is created this
properly refer to the correct object (an instance of slideshow). The reason we can access the self variable during event callback is because it has been captured by a closure.
Feel free to google or search on stackoverflow any word/terminology from the above description if you need further explanation.
slideshow=function(){
var g = document.createElement(...);
g._objRef = this;
...
g.onclick = f1;
f1 = function(event) {
alert(this._objRef);
}
}
var sl1 = new slideshow();
var sl2 = new slideshow();
A bit of a hack imo, but it should do the trick.
精彩评论