What is the difference between “this”, “$this” and “$(this)”?
In typical usage you'll usually see them like this (the $this
usage may vary):
this
- Refers to the DOM element in the handler you're currently on, but this may be another object entirely in other situations, but it's always the context.$this
- Usually created byvar $this = $(this)
a cached version of the jQuery wrapped version for efficiency (or chain off$(this)
to get the same in many cases).$(this)
- The jQuery wrapped version of the element, so you have access to all its methods (the ones in$.fn
specifically).
jquery this versus $(this) and maybe even $this
this
is a JavaScript thing. It refers to the "context" a function is running in. For most event handlers, it is the ("raw") DOM element that is listening to an event. In other situations it will mean other things; Googling "this
in JavaScript" might be enlightening.
I say it is the "raw" DOM element because jQuery is often used to wrap plain DOM elements in a jQuery wrapper, so you can use jQuery methods like attr
instead of the usual ones (getAttribute
, setAttribute
, etc.). This wrapping is accomplished with the $
function, and that's where you see $(this)
. For example:
this.getAttribute("href")
/* or */ someElement.getAttribute("href")
is the same as
$(this).attr("href")
/* or */ $(someElement).attr("href")
$this
or this$
is just a variable name. But, it is often conventional to do an assignment like
var $this = $(this);
The reason for this is to avoid continually invoking the $
function, which is somewhat expensive as it creates a new jQuery wrapper object every time. If you store the wrapped element in a variable, you gain slightly in efficiency.
In rare cases, this
might already be a jQuery wrapper. The case that comes up often for me is when writing jQuery plugins. In that case you can do things like this.attr("id")
directly, without wrapping it up first, because it's already wrapped. In the usual cases (event handlers, $.each
, etc.) the wrapper is necessary.
Turn '$(this)' jquery to javascript 'this'
jQuery is set based, and lets you access the elements of that set using either indexer notation ([]
) or the get
method.
So if you have a jQuery set:
var set = $(this);
...you can access its elements via set[0]
through set[set.length - 1]
and via set.get(0)
through set.get(set.length - 1)
(get
also supports negative indexes for indexing from the end).
In the case of $(this)
, of course, you don't need to use $()
at all — just use this
directly. This is true whenever you have a raw DOM reference, whether this
or event.target
or whatever.
Jquery : Understanding Syntax
Actually, init: function() { }
isn't an anonymous function at all. I will try to answer the numerous parts of your question as best as possible.
ContactForm
is an object, and thus has properties and methods that can be accessed through JS. For example, you may access the show()
and close()
methods from outside of the object by using its literal name, for example:
ContactForm.show();
ContactForm.close();
Since it is an object, you may also reference it by using the this
keyword inside of it. For example, if you wanted to call the show()
method from inside the init()
method, you could do this:
var ContactForm = {
init: function()
{
this.show(); // using this keyword.
},
show: function()
{
},
close: function()
{
}
}
In this particular instance, this
=== ContactForm
. However, the syntax you indicated of $(this)
is used to create a jQuery object (or collection) from a DOMElement object. For example, let's say that you wish to bind a callback function to an element's click
event:
$('a').on('click', function() {
$(this) // <-- This now holds a jQuery object representing the clicked element
});
So, bearing all of that in mind:
Within the show()
method, the first line calls the close()
method of the ContactForm
object. The code makes use of the Function's prototype call()
method, which allows us to specify the value of this
inside of the function. So, on the following line:
ContactForm.close.call(ContactForm.container);
The code is sending ContactForm.container
(which is a jQuery object) to the close()
method, so that it may be accessed by this
:
var $this = $(this);
Inside of the close()
method, this
now === $('#contact')
and not ContactForm
.
Wrap all text that starts with a certain word
Admittedly wasn't specific with my question the first time around, but I managed to get my answer regardless.
$('.content').html($('.content').html().replace(/@([^\s]+)/g,'<a href="$1">@$1</a>'));
This will wrap all code starting with "@" in an element.
Difference between $(shell ...) and $$(...) in make
$(shell ...)
is a Make text function. Make will expand this, so in your example, a
will expand, when substituted, to the result of the find
command. (If you made it a simply-expanded variable, the shell command would be evaluated only once, of course).
$$
is just expanded to $
, so in your example, b
will substitute as the value $(find . -maxdepth 1 -type f -name "Makefile")
. This will be the same whether b
is defined with =
or :=
.
When you use $(b)
in a command such as echo $(b)
, the shell running that command will see this as command substitution. In other words, you have echo $(find ...)
as a shell command.
Using $(b)
in a Make target or dependency will, as you have seen, perform no further evaluation.
Here's another example Makefile, which I hope demonstrates what's going on. We use single-quotes to show literally what the shell is given:
a = $$(echo true)
b = $(shell echo true)
print:
echo '$$a: $a' = "$a"
echo '$$b: $b' = "$b"
.PHONY: print
This gives me
echo '$a: $(echo true)' = "$(echo true)"
$a: $(echo true) = true
echo '$b: true' = "true"
$b: true = true
showing that in the first case, the shell is given $(echo true)
in its command, whereas in the second case, Make evaluates echo true
and simply substitutes the result true
into the command.
Javascript function that can be used by many elements and then distinguish which element clicked it
In the event handler you are trying to compare the this
object to a string.
The this
in the context of the jQuery callback is the element that was clicked. If you wish to compare who was clicked you have to use this.id
which in context of the first month will equal January
. So you can compare.
if(this.id == "January") {
$(this).addClass("highlight");
$(".january").addClass("show");
}
There are some other approaches you can take to save on some code.
$("#January,#February,#March,#April").click(function(e) {
var monthStr = this.id;
$(".month").removeClass("highlight");
$(".month_sections").removeClass("show");
$(".month_sections").addClass("hide");
$(this).addClass("highlight");
$("." + monthStr.toLowerCase()).addClass("show");
});
I hope this is useful.
Related Topics
What Is the Temporal Dead Zone
Get the Current Url With JavaScript
How to Find the Sum of an Array of Numbers
JavaScript: Natural Sort of Alphanumerical Strings
Resolve Promises One After Another (I.E. in Sequence)
What Is the Purpose of Node.Js Module.Exports and How to Use It
Get JavaScript Object from Array of Objects by Value of Property
How to Declare a Namespace in JavaScript
Location of Parenthesis For Auto-Executing Anonymous JavaScript Functions
How to Parse CSV Data With JavaScript
How to Add Two Strings as If They Were Numbers
Use Basic Authentication With Jquery and Ajax
Updating Address Bar With New Url Without Hash or Reloading the Page
Async/Await Implicitly Returns Promise
Remove Empty Elements from an Array in JavaScript
Rails 4: How to Use $(Document).Ready() With Turbo-Links
When Are You Supposed to Use Escape Instead of Encodeuri/Encodeuricomponent