{"id":159,"date":"2023-12-03T19:39:12","date_gmt":"2023-12-04T00:39:12","guid":{"rendered":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/?p=159"},"modified":"2023-12-03T19:39:17","modified_gmt":"2023-12-04T00:39:17","slug":"whats-this-whats-this","status":"publish","type":"post","link":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/whats-this-whats-this\/","title":{"rendered":"What&#8217;s this? What&#8217;s&#8230; this?"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The <code>this<\/code> keyword is a notorious roadblock on the path to grasping JavaScript. Just referring to it sounds funny &#8211; &#8220;the this&#8221; &#8211; the what now? Understanding <code>this<\/code> is key to becoming an adept JS programmer, though. So let&#8217;s break it down.<\/p>\n\n\n\n<h2 class=\"wp-block-heading has-extra-large-font-size\">Prereqs for understanding &#8216;this&#8217;<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>this<\/code> keyword is primarily used in the context of <em>Object Oriented Programming<\/em>, which is a whole thing in and of itself. If you\u2019re not yet familiar with what objects are and the general gist of OOP, this (pun intended) might be a good time to check out the link and orient yourself before proceeding.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In order to fully understand all the possible meanings of <code>this<\/code>, you\u2019ll also need to know what <em><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Building_blocks\/Events\">events<\/a><\/em>,<em> <a href=\"https:\/\/www.w3schools.com\/js\/js_object_methods.asp\">object methods<\/a><\/em>, and <em><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Scope\">scope<\/a><\/em> are, and to really really get it, what <em><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Strict_mode\">strict mode<\/a><\/em> is. I\u2019m actually going to save strict mode for another post, so for now just know that it\u2019s a thing, and changes what <code>this<\/code> can mean.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lastly, you need to keep in mind that <code>this<\/code> is a <em>keyword<\/em>, not a variable. You can\u2019t change the meaning of <code>this<\/code> in a direct way like you would a variable. Its meaning is all dependent on <em>how<\/em>, aka <em>the context<\/em> in which it\u2019s used.<\/p>\n\n\n\n<h2 class=\"wp-block-heading has-extra-large-font-size\">The definition<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In JavaScript, in non-strict mode, <strong>the <code>this<\/code> keyword refers to an object<\/strong>. Sounds simple, right?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The tricky part is understanding <em>which<\/em> object <code>this<\/code> refers to, because which object <code>this<\/code> refers to all depends on <em>how<\/em> <code>this<\/code> is being invoked.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, let\u2019s take a look at the different ways <code>this<\/code> can be invoked, and we\u2019ll identify which objects it refers to based on each context. After we run through the different contexts, we\u2019ll look at a series of questions you can ask yourself to narrow down which context applies.<\/p>\n\n\n\n<h2 class=\"wp-block-heading has-extra-large-font-size\">All the Objects<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In an <strong>object method<\/strong>, <code>this<\/code> refers to the <strong>object<\/strong> the method belongs to.<\/li>\n\n\n\n<li>Alone, in the global scope, <code>this<\/code> refers to the <strong>global object<\/strong>.<\/li>\n\n\n\n<li>In a function, <code>this<\/code> refers to the <strong>global object<\/strong>.<\/li>\n\n\n\n<li>In an <strong>event<\/strong>, <code>this<\/code> refers to the <strong>DOM element<\/strong> that <em>received<\/em> the event.<\/li>\n\n\n\n<li>Methods like <code>bind()<\/code>, <code>call()<\/code>, and <code>apply()<\/code> can make <code>this<\/code> refer to <strong>any object<\/strong>.<\/li>\n\n\n\n<li>*In <strong>strict mode<\/strong>, <code>this<\/code> can be <strong>any value<\/strong>. Woah! Don&#8217;t worry about strict mode for now, though. Just know that it&#8217;s the only context in which <code>this<\/code> doesn&#8217;t stick to the basic rule of always referring to an object.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Okay, that&#8217;s a lot, and far too concise for practical understanding, so let&#8217;s dig in to each context a little more.<\/p>\n\n\n\n<h3 class=\"wp-block-heading has-large-font-size\">In an Object Method<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Whenever <code>this<\/code> is used in a method that&#8217;s defined in an object, it refers to that object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Take the classic example of defining a <code>person<\/code> object literal:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const person = {\n  firstName: \"Jane\",\n  lastName: \"Doe\",\n  fullName() {\n    return this.firstName + \" \" + this.lastName;\n  }\n};\n\nperson.fullName(); \/\/ returns Jane Doe<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above, <code>fullName()<\/code> is a method of the <code>person<\/code> object. Because <code>this<\/code> is being used inside of <code>fullName()<\/code>, we know it refers to <code>person<\/code>, and any properties we append <code>this<\/code> with will be properties of <code>person<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">*An important note about object methods and <code>this<\/code> \u2013 the method has to be defined either using the <code>function<\/code> keyword, or the concise syntax used above. If an <code>=><\/code> arrow function is used, the value of <code>this<\/code> is not bound to the containing object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading has-large-font-size\">Alone<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When <code>this<\/code> is used alone, meaning hangin\u2019 out there in the global scope, outside of any function, object or method, it refers to the <strong>global object<\/strong>. This is rare, but good to know about.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>this.x = 2; \/\/ sets x property of global object\nconsole.log(x) \/\/ prints 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, what the global object actually <em>is<\/em> depends on what environment we\u2019re in. In a browser environment, the global object is <code>window<\/code>. In an environment like Node.js, the global object just means the global scope, which we shouldn\u2019t be polluting in the first place.<\/p>\n\n\n\n<h3 class=\"wp-block-heading has-large-font-size\">In a Global Function (non-strict mode)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In similar fashion to when <code>this<\/code> is used alone in the global scope, when <code>this<\/code> is in a function in the global scope, the <strong>global object<\/strong> is also the default binding. That\u2019s because <em>all<\/em> global variables, including global functions, are properties of an unnamed global object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function f(x) {\n  this.y = x + 1;\n}\n\nf(2); \/\/ f is called as a global function\nconsole.log(y); \/\/ prints 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above, the <code>f()<\/code> function is in the global scope, so <code>this.y<\/code> sets a y property of the global object with a value equal to whatever argument is passed to <code>f()<\/code> plus 1.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">*Remember that invoking a function with the <code>new<\/code> keyword is not the same as defining a global function. Functions invoked with <code>new<\/code> create new objects, so any use of <code>this<\/code> inside of them would refer to the object being created, just like with our first example on object methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading has-large-font-size\">In Events<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In event handlers, <code>this<\/code> refers to the DOM element that receives the event.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of a button with a click event:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;button onclick=\"this.style.display='none'\">\n  Click to make me disappear\n&lt;\/button><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>&lt;button><\/code> element is what receives the click event, so when the button gets clicked, <code>this<\/code> is referencing the <code>&lt;button><\/code> element, and sets its <code>display<\/code> property to <code>none<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading has-large-font-size\">In apply(), call(), and bind()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The predefined JavaScript methods <code>apply()<\/code>, <code>call()<\/code>, and <code>bind()<\/code> let you <em>explicitly<\/em> define the object you want to use as the value of <code>this<\/code>. Doing so is called <em>explicit function binding<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s try an example with the <code>call()<\/code> method. Here&#8217;s the syntax for <code>call()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function.call(thisArg, arg1, arg2, ...)<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>thisArg<\/code> is the object we want to make <code>this<\/code> refer to.<\/li>\n\n\n\n<li><code>arg1<\/code>, <code>arg2<\/code>, and so on are individual arguments that we want to pass to the function we&#8217;re invoking.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Now, here we have a <code>greet()<\/code> function that uses the <code>name<\/code> property of the object to which <code>this<\/code> refers. It takes a <code>message<\/code> parameter and logs a greeting using that message and a name value. We\u2019re going to use <code>call()<\/code> to invoke <code>greet()<\/code> and explicitly set the object that we want the <code>name<\/code> property of.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function greet(message) {\n  console.log(message + ', ' + this.name);\n}\n\nconst person1 = { name: 'Jane' };\nconst person2 = { name: 'John' };\n\n\/\/ use call to set 'this' to the person object\ngreet.call(person1, 'Hello'); \/\/ Hello, Jane\ngreet.call(person2, 'Hey');   \/\/ Hey, John<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When <code>call()<\/code> invokes <code>greet()<\/code> the first time, it specifies <code>person1<\/code> as the context, and passes \u2018Hello\u2019 as the <code>message<\/code> argument. So, when <code>greet()<\/code> is executed, <code>this<\/code> refers to the <code>person1<\/code> object where the <code>name<\/code> value is Jane.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When <code>call()<\/code> invokes <code>greet()<\/code> again, it\u2019s in the context of <code>person2<\/code>, and uses a different message. So we get \u201cHey, John\u201d logged to the console.<\/p>\n\n\n\n<h2 class=\"wp-block-heading has-extra-large-font-size\">How do I know?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you\u2019re not totally sure which object <code>this<\/code> refers to because more than one context might be influencing its meaning, we can use the following order of precedence:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><code>bind()<\/code><\/li>\n\n\n\n<li><code>apply()<\/code> and <code>call()<\/code><\/li>\n\n\n\n<li>Object method<\/li>\n\n\n\n<li>Global scope<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">So, you can ask yourself the following questions in order, and the first one you answer \u201cyes\u201d to will tell you what context takes precedence:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Is <code>this<\/code> in a function being invoked with <code>bind()<\/code>?<\/li>\n\n\n\n<li>Is <code>this<\/code> in a function being invoked with <code>apply()<\/code> or <code>call()<\/code>?<\/li>\n\n\n\n<li>Is <code>this<\/code> in an object method?<\/li>\n\n\n\n<li>Is <code>this<\/code> in a function in the global scope?<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">And there you have it! Err&#8230; there you have <code>this<\/code>!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The this keyword is a notorious roadblock on the path to grasping JavaScript. Just referring to it sounds funny &#8211; &#8220;the this&#8221; &#8211; the what now? Understanding this is key to becoming an adept JS programmer, though. So let&#8217;s break it down. Prereqs for understanding &#8216;this&#8217; The this keyword is primarily used in the context [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":160,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[5,15,16],"class_list":["post-159","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-frontend","tag-guide","tag-programming"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-content\/uploads\/2023\/12\/pexels-photo-1981863.jpeg","_links":{"self":[{"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/posts\/159","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/comments?post=159"}],"version-history":[{"count":1,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/posts\/159\/revisions"}],"predecessor-version":[{"id":161,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/posts\/159\/revisions\/161"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/media\/160"}],"wp:attachment":[{"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/media?parent=159"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/categories?post=159"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wcet.waketech.edu\/abthomas3\/web250\/wordpress\/wp-json\/wp\/v2\/tags?post=159"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}