concept reference in category javascript
appears as: reference, references

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.
Listing 4.6. The differences between function and method invocations
function whatsMyContext() { #A return this; #A } #A assert(whatsMyContext() === window, #B "Function call on window"); #B var getMyThis = whatsMyContext; #C assert(getMyThis() === window, #D "Another function call in window"); #D var ninja1 = { #E getMyThis: whatsMyContext #E }; #E assert(ninja1.getMyThis() === ninja1, #F "Working with 1st ninja"); #F var ninja2 = { #G getMyThis: whatsMyContext #G }; #G assert(ninja2.getMyThis() === ninja2, #H "Working with 2nd ninja"); #H #A - Returns the function context that will allow us to examine the context from outside #B - Invoking as a function sets the context to the window object. #C - getMyThis gets a reference to the whatsMyContext function. #D - Invokes the function using the getMyThis variable. Even though we use a variable, the function is still invoked as a function, and the function context is the window object. #E - A ninja1 object is created with a getMyThis property that references the whatsMyContext function. #F - Invoking the functions through getMyThis calls it as a method of ninja1. The function context is now ninja1. That’s object orientation! #G - Another object, ninja2, also has a getMyThis property referencing whatsMyContext. #H - Invoking the function as a method of ninja2 shows that the function context is now ninja2. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!
The idea of prototyping is simple. Every object can have a reference to its prototype, an object to which the search for a particular property can be delegated to, if the object itself doesn’t have that property. Imagine that you’re in a game quiz with a group of people, and that the game show host asks you a question. If you know the answer, you give it immediately, and if you don’t, you ask the person next to you. It’s as simple as that.
Listing 7.5. Examining the type of an instance and its constructor
function Ninja(){} const ninja = new Ninja(); assert(typeof ninja === "object", #A "The type of the instance is object."); assert(ninja instanceof Ninja, #B "instanceof identifies the constructor." ); assert(ninja.constructor === Ninja, #C "The ninja object was created by the Ninja function."); #A - Tests the type of ninja via typeof. This tells us it’s an object, but not much else. #B - Tests the type of ninja via instanceof. This provides more information—that it was constructed from Ninja. #C - Tests the type of ninja via the constructor reference. This gives a reference to the constructor function. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!