我不是最擅长jquery,而且我遇到了一个var初始化,我不知道为什么编写代码的人这样做。
在插件的初始化中,我们有
this.init = function(settings) {
var $this = this;
this.s = {
initialSlide: 0,
firstSlide: true,
};
... more code, some uses $this, some uses "this"
}
那么“$this”和“this”之间有什么区别,为什么不一直使用其中一个呢?
最佳答案
通常,这意味着this
的副本。 this
的特点是它在每个函数中都会发生变化。然而,以这种方式存储它可以防止 $this
发生变化,而 this
确实会发生变化。
jQuery 大量使用了神奇的 this
值。
考虑这段代码,您可能需要像您所看到的那样的东西:
$.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
});
};
关于javascript - var $this = this 的原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7234282/