我不是最好的jquery,我遇到了一个var初始化,我不知道编写代码的人为什么会这样做。
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.
在插件的init中,我们有
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" }那么$ this和this之间有什么区别?为什么不一直使用一个或另一个?
So what is the difference here between "$this" and "this" and why not use one or the other all the time?
推荐答案通常,这意味着此的副本。关于这个的事情是它在每个函数中都会发生变化。但是,以这种方式存储会使 $ this 保持不变,而此确实会发生变化。
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大量使用魔法这个值。
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 }); };更多推荐
var $ this = this的原因是什么?
发布评论