Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  107] [ 4]  / answers: 1 / hits: 23621  / 13 Years ago, mon, august 29, 2011, 12:00:00

I'm not the best at jquery and I came across a var initialization that I don't know why the person who wrote the code did it this way.



In the init for a plugin, we have



this.init = function(settings) {
var $this = this;
this.s = {
initialSlide: 0,
firstSlide: true,
};
... more code, some uses $this, some uses this
}


So what is the difference here between $this and this and why not use one or the other all the time?


More From » jquery

 Answers
2

Generally, this means a copy of this. The thing about this is that it changes within each function. Storing it this way, however, keeps $this from changing whereas this does change.



jQuery heavily uses the magic this value.



Consider this code, where you might need something like you are seeing:



$.fn.doSomethingWithElements = function() {
var $this = this;

this.each(function() {
// `this` refers to each element and differs each time this function
// is called
//
// `$this` refers to old `this`, i.e. the set of elements, and will be
// the same each time this function is called
});
};

[#90359] Saturday, August 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
;