![]() The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. When you instantiate a JavaScript constructor function, an object is returned. But we don’t simply execute Foo we instantiate it: var bar = new Foo(). If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). ![]() When you look at the code, it seems as if “this” will refer to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. The “instances” are JavaScript objects, but they differ from object literals in a few ways.įor an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.Įarlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. ![]() When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. In other words, the variable “bar” becomes an instance of “Foo”. ![]() When we instantiate Foo, we assign that instantiation to the variable: “bar”. We’ve also created a constructor function named “Foo”. ![]()
0 Comments
Leave a Reply. |