var $ this = this的原因是什么?

我不是最好的jquery,我遇到了一个var初始化,我不知道为什么编写代码的人这样做了。

在插件的init中,我们有

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`, ie the set of elements, and will be // the same each time this function is called }); }; 

在这种情况下,没有。 $this只是另一个赋值给它的变量声明。

通常情况下,我已经看到了包装this时使用JavaScript库的人使用的这种快捷方式。 例如,jQuery中的典型用法是:

 // rather than writing $(this) everywhere var $this = $(this); $this.each(function(){ // Do Something }); 

在这种情况下,它没有任何意义(没有双关语)。 如果语句是var $this = $(this)则更合乎逻辑,因为这样可以使用所有漂亮的jQueryfunction。

其他人都说过,jquery代码中还有一个成语,用j来为jquery对象加前缀。 不知道它有多受欢迎,但过去常常看到很多。

我做$ this = $(this)因为它似乎每次你想要使用它时都会保存该调用的实际处理。

此外,对于’魔术’这个’其他人提到的function。 保持原始副本是很方便的。

实际上,jQuery是JavaScript DOM的包装器,它既增强又简化了它。 非常简单的JQuery选择器返回JQuery Object / s即

 var jQueryResults = $("article"); //Contains all article elements in the DOM as JQuery objects 

但是,使用Javascript选择元素会返回HTML DOM元素,即

 var normalResults = document.getElementsByTagName("article");//Contains all article elements in the DOM as HTML objects 

出现的问题是DOM对象不提供与JQuery对象相同的function。

这是一个事件示例,说明了差异:

 $('.changeColorHover').hover(function() { this.attr("style", "color:red"); }); //Will not work as we are trying to call a JQuery method on a DOM object 

考虑到上面提到的’this’关键字是一个DOM对象,因此您需要将其转换为jQuery对象才能使用jQuery方法。

  $('.changeColorHover').hover(function() { $(this).attr("style", "color:red"); }); //Will work since we have first converted the DOM object to a JQuery object 

总而言之,this关键字允许您访问调用事件的对象,因为这将引发引发事件的对象。 但是,这是一个DOM对象,而不是一个jQuery对象。 因此,除非将其转换为jQuery对象,否则您要使用的任何jQuery方法都不可用。