![]() ![]() In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: Example # 2Ĭonsole. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. So, in Example # 1, the getMusic method returns “this.music”. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated. 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. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |