Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - What is the reason for var $this = this

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...