0

I've tried to google my question but it makes me even more confused. My question is:

Here's the jQuery code:

$(document).ready(function() {  
    $(window).resize(function() {
        if ($(this).width() < 200) {
          $("p").css("color", "red");
        } else {
          $("p").css("color", "green");
        }
    });  
}

Why do we write (this) and not ("this") ?

How do I know if (document) and (window) should be written with " " - and why's that?

Maybe you could link me somewhere that explains my issue. My code apparently works either way, I'm just curious about the why.

3
  • Anything in " is a string. You want a variable/object: this. Same with document and window - they're objects. When you do $("selector") you're passing a string, eg "#myid" Commented Nov 28, 2021 at 11:51
  • 1
    Wonderful! Is my code an anonymous function btw and why? I'd rather not post a new thread for this tiny question. Commented Nov 28, 2021 at 11:57
  • @HTML_Newbie please view my answer and mark it as the answer if it was helpful Commented Dec 21, 2021 at 11:54

1 Answer 1

2

In JavaScript namespace, this is reserved [source].

The JavaScript object literal this refers to the inherited object from the present state in the current execution.

Another example of this we can see is when we are looping through an array and the object this would symbolize the current array object. You may, for example, see this.title, or this.description if we were iterating through a database array of blog posts.

this in jQuery refers to the inherited object. When we add the quotation marks, and it becomes a string, such as "this". This makes jQuery parse it as a DOM selector.

Then we are now looking for the HTML DOM selector <this>, which to my knowledge, does not actually exist in the accepted HTML syntax standards.

As otherwise stated, the concept of this will become tricky when you are working in other JavaScript environments, such as React or Angular. Within the context of a functional component, this becomes the state, such as handling user sessions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.