JS225 Object Oriented JavaScript

¡Supera tus tareas y exámenes ahora con Quizwiz!

JS225 Function Contexts and Objects Summary

- Function invocations (e.g., parseInt(numberString)) rely upon implicit execution context that resolves to the global object. Method invocations (e.g., array.forEach(processElement)) rely upon implicit context that resolves to the object that holds the method. - All JavaScript code executes within a context. The top-level context in a web browser is the window object. All global methods and Objects (such as parseInt or Math) are properties of this object. In Node, the top-level context is called global. However, be aware that Node has some peculiarities that cause it to behave differently from browsers. - You can't use delete to delete variables and functions declared at the global scope. - this is the current execution context of a function. - The value of this changes based on how you invoke a function, not how you define it. - In strict mode, this inside functions resolve to undefined when referring to the global execution context. - JavaScript has first-class functions which have the following characteristics: You can add them to objects and execute them in the respective object's contexts. You can remove them from their objects, pass them around, and execute them in entirely different contexts. They're initially unbound, but dynamically bound to a context object at execution time. - call and apply invoke a function with an explicit execution context. - bind permanently binds a function to a context and returns a new function - Method invocations can operate on the data of the owning object

What are the characteristics that define higher-order functions in JavaScript?

A higher-order function must either: 1.) Take a function as an argument, 2.) return a function, 3.) or Both.

Gentle explanation of 'this' keyword in JavaScript: Pitfall: separating method from its object.

A method from an object can be extracted into a separated variable var alone = myObj.myMethod. When the method is called alone, detached from the original object alone(), you might think that this is the object on which the method was defined. if the method is called without an object, then a function invocation happens: where this is the global object window or undefined in strict mode.

At it's core, what is object-oriented programming?

A pattern that uses objects as the basic building blocks of a program instead of local variables and functions. The object-oriented approach to programming puts data and procedures that manipulate that data into containers for that data, i.e., objects. We no longer deal solely with primitives, or composites of primitives, but "smart" objects that can perform actions on the data they own. This way, we move complexity inside objects instead of exposing it globally. When we must make changes, we can restrict those changes to those objects; they don't ripple throughout the entire project. Maintenance is easier when we can limit the scope of changes.

What will the code below output? What would happen if we replaced var on line 1 with let? Can you explain why the output changes? var a = 10; let b = 10; let c = { a: -10, b: -10, }; function add( ) { return this.a + b; } c.add = add; console.log(add( )); console.log(c.add( ));

As in question 3, the key detail here is that the first invocation of add is as a function, while the second invocation is as a method. In the function invocation, on line 14, this resolves to the global object, and the property a to the value 10. In the method invocation, however, this resolves to the object c, and the property a to the value -10. In both cases a simple reference to b. When we replaced var with let, the output of the function call is NaN, not 20. This happens because global var variables create properties on the global object, but let and const create variables that don't belong to any object.

JavaScript: concise method syntax

As you may have seen in some previous material, you can also define methods with a concise notation. The new concise method shorthand lets you eliminate the : and the word function. You can mix and match the different styles in a single object. However, you should use a consistent style within each object definition.

In regards to objects and closures in JavaScript, having a function that returns a function may provide a concise solution but the interface can be somewhat unclear. How can we remedy this?

If you refer back to our makeList function, the function returned lets the user perform three different actions (adding, removing, and listing) by calling the function with appropriate arguments. This code works, but it's unclear. In fact, the single call list('make breakfast') can perform two entirely different operations based on the current state of the list! We can improve the interface by returning an Object from makeList instead of a single Function. If we do that, we can create an API that is easy to use and understand. This example is much easier to understand since it uses the property names of methods to reveal the code's intent. The implementation is simpler since each well-named method does one thing.

Dealing with Context Loss: Methods lose context when taken out of their respective object.

If you remove a method from its containing object and execute it, it loses its context. You could use foo.call(john) to restore the context, but what happens if you don't want to execute the function right away, or you need to pass it to another function? By the time you're ready to call foo, john may be out of scope. To fix this, you can update the receiving function (repeatThreeTimes) by adding an extra parameter to the function and pass in the desired context and change func( ) to func.call(context)

In JavaScript what are the two types of execution contexts?

Implicit: This is an execution context that JavaScript "implicitly" sets. Explicit: This is an execution context that you "explicitly" set.

With strict mode not enabled, what object serves as the implicit execution context? What happens when strict mode is enabled?

In strict mode, the global object is not accessible as the implicit execution context. When disabled, the implicit execution context is global or window.

An example of using bind.

In this example, we bind the greeting function to the spanishWords object and assign the result to spanishGreeter. When we call spanishGreeter, JavaScript uses spanishWords as the this value. Hence, spanishGreeter('Jose') will log something like 'Buenas tardes, Jose' instead of 'Good afternoon, Jose'.

In JavaScript, what is the global object and when is it created?

Is created when it starts running, which serves as the implicit execution context. In the browser, the global object is the window object. In non-browser JavaScript environments, such as Node, the global object is not window, but global. As with other JavaScript objects, you can add properties to the global object at any time.

For an extra challenge, consider this line of code from the previous problem: let args = [ ].slice.call(arguments); Inside of JavaScript functions, arguments is an object that holds all of the arguments passed to the function. Bearing in mind that the function author wants to iterate over the arguments later in the method using an Array method, why do you think he or she is invoking call?

It isn't possible to call forEach on arguments since it is only Array-like and not an array. However, since it is Array-like (having indices from 0 to length - 1) we can use it as the context to a slice method call on an empty array. The return value assigned to args is an array holding all of the arguments passed to the outputList function since we are executing slice with no arguments passed to it (recall: the first value passed to call is a the execution context). Modern JavaScript doesn't use the built-in arguments object. Instead, it uses the new rest syntax that we discuss in our Syntactic Sugar gist:

What does the code below do? function func( ) { let b = 1; } func(); console.log(b);

It raises a referenceError: b is not defined. This code throws a ReferenceError, because the variable declaration on line 2 (which is executed when func is invoked on line 5) occurs in function scope. Thus, it isn't a property on the global object and isn't accessible outside the function.

When we declare global variables with var or functions, what does JavaScript do with them?

JavaScript adds them to the global object as properties.

Hard Binding Functions with Contexts?

JavaScript has a bind method that lets us bind a function to a context object permanently. Unlike call or apply, bind doesn't execute a function. Instead, it creates and returns a new Function, and permanently binds it to a given object. Since the binding is permanent, we can pass the function around without concern that its context will change; it won't.

When does a function get it's execution context in JavaScript?

JavaScript has first-class functions which means the developer can add them to objects, execute them in the context of those objects, remove them from their objects, pass them to other functions, and run them in entirely different contexts. First-class Functions initially have no context; they receive one when the program executes them.

JavaScript Explicit Function Execution Context?

JavaScript lets us use the call and apply methods to change a function's execution context at execution time. That is, we can explicitly bind a function's execution context to an object when we execute the function. Top Code: On line 13, we explicitly bind the execution context of foo to object. Thus, this on line 9 references object instead of the global object. Bottom Code: Here, we run foo from strings in the numbers context. We're "borrowing" a method from an object to use with another object; we're not copying it.

Node JS Module Scope and this

None of the above variables are properties of this. The reason for this odd behavior is that Node wraps files in this odd looking function. That means all of your variables and functions in Node programs have function scope. That plays a part later when we learn about execution context: the execution context for your top-level program in Node is the empty object, {}.

What does the code below log? a = 10; console.log(window.a === a);

Note that strict mode is not enabled. This code logs true. Initializing an undeclared variable, as we do on line 1 in the code above, automatically creates that variable as a property on window since the global object is the implicit context for evaluating expressions.

What does the code below log? "use strict" a = 10; console.log(window.a === a);

Nothing is logged as line 1 raises a ReferenceError. In strict mode, using variables that have not been previously declared is not allowed. Since a was not previously declared, the assignment on line 1 raises an error.

What will the code below log to console? let obj = { message: 'JavaScript', }; function foo( ) { console.log(this.message); } foo.bind(obj);

Nothing. Unlike call and apply, bind doesn't invoke the receiver function. Rather, it returns a new function that is permanently bound to the context argument.

This example shows that binding a function to a context object occurs when you execute the function, not when you define it.

On line 9, we set bar to point to object's foo method. When we call bar, JavaScript implicitly binds the method to the global object instead of object.

What will the code below output? let obj = { a: 'Amazebulous!', }; let otherObj = { a: "That's not a real word!", }; function foo( ) { console.log(this.a); } let bar = foo.bind(obj); bar.call(otherObj);

Once a function has been bound to an execution context with bind, its context can't be changed, even explicitly. In keeping with this, the last line of our code outputs Amazebulous!, because the function bar has been bound to obj. Thus, inside of bar, this points to obj when bar is invoked on the last line, rather than otherObj, despite the fact that the function is being invoked by call with otherObj as the explicit context argument.

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in a function definition when using strict mode? What about outside any function scope?

Once enable, the strict mode mode affects the execution context, making this to be undefined in a regular function invocation. The execution context is not the global object anymore.

Dealing with Context Loss: Internal Function losing method context, Solution 1: Preserve Context with a local variable in the lexical scope.

One common approach is the let self = this or let that = this fix. You save this in a variable named self or that before calling the function, then reference the variable in the function. Here we assign this to a local variable self on line 5. Based on its lexical scope, bar has access to self, so it can freely use self instead of this to access the proper context object.

In JavaScript, Since forEach expects a function, how can we form the syntax in an even shorter way to achieve iteration?

Since forEach expects a function, and that function receives an array element value as its first argument, all we have to do is pass forEach the name of a function that meets those requirements.

Consider the code below: let foo = { a: 0, incrementA( ) { function increment( ) { this.a += 1; } increment( ); } }; foo.incrementA( ); foo.incrementA( ); foo.incrementA( ); What will the value of foo.a be after this code has executed?

Since inner functions lose the outer object as context, this.a on line 5 references a global a, rather than foo's property a. As a result, foo.a is unaltered by the method invocations, and its value remains 0.

In the code below, use call to invoke add as a method on bar, but with foo as the execution context. What will this return? let foo = { a: 1, b: 2, }; let bar = { a: 'abc', b: 'def', add( ) { return this.a + this.b; }, };

Since we are invoking call on bar.add and supplying the object foo as explicit context, foo's properties a and b, rather than bar's, will be referenced during execution, returning a value of 3.

Dealing with Context Loss: Function as Argument Losing Surrounding Context, Solution 3: Use the optional thisArg argument.

Some methods that take function arguments allow an optional argument that defines the context to use when executing the function. Array.prototype.forEach, for instance, has an optional thisArg argument for the context. This argument makes it easy to work around this context loss problem. Array.prototype.map, Array.prototype.every, and Array.prototype.some also takes an optional thisArg argument.

In JavaScript, we don't need code to claim and release memory; the JavaScript runtime handles that for us. It gets memory from the system when we create new objects and primitive values and releases it when the program has no more references to them.

That is, when there are no variables, objects, or closures that maintain a reference to the object or value, JavaScript marks the memory as eligible for GC. This concept is important. As long as the object or value remains accessible, JavaScript can't and won't garbage collect it.

What will the code below output? function foo( ) { return this; } let context = foo( ); console.log(context);

The code logs the browser's global object, Window or global (depending if using node or browser) The return value of the foo function is the value of the global object (global). We assign context to that variable, then display it to show the value of global.

JavaScript Implicit Method Execution Context?

The execution context for any method (i.e., function referenced as an object property) invoked without an explicit context provided. JavaScript implicitly binds methods invoked in this manner to the owning or calling object.

What will the code below output? var message = 'Hello from the global scope!'; function deliverMessage( ) { console.log(this.message); } deliverMessage( ); let bar = { message: 'Hello from the function scope!', }; bar.deliverMessage = deliverMessage; bar.deliverMessage( );

The first log operation is generated by the function call, deliverMessage() on line 7. Since this is a function invocation, the implicit function execution context is the global object, Window. That means that JavaScript looks in Window for the variable message. The second log operation is generated by the method call bar.deliverMessage() on line 15. Since the implicit function execution context for a method invocation is the calling object, this resolves to bar, and this.message resolves to bar's property message.

JavaScript, global declarations vs global object as implicit context.

The global object is the implicit context when we evaluate expressions. For example, in the code above, the first line doesn't declare a global variable since it doesn't use the let, var, or const keyword. It works, though, since JavaScript gives foo an implicit evaluation context: the global object. Thus, the first line is the same as window.foo = 1, which assigns the property foo on the global object with a value of 1. On line 2, since there are no local or global variables named foo, JavaScript looks in the implicit context of the global object and finds the foo property. As a result, line 2 is identical to window.foo; it returns the value of the property foo from the global object.

Dealing with Context Loss: What happens if you can't update the function or can't supply a context object?

Then you need a different approach. Hard binding with bind often works.

Any difference between First Class Function and High Order Function?

There is a difference. When you say that a language has first-class functions, it means that the language treats functions as values - that you can assign a function into a variable, pass it around etc. Higher-order functions are functions that work on other functions, meaning that they take one or more functions as an argument and can also return a function. The "higher-order" concept can be applied to functions in general, like functions in the mathematical sense. The "first-class" concept only has to do with functions in programming languages. It's seldom used when referring to a function, such as "a first-class function". It's much more common to say that "a language has/hasn't first-class function support". The two things are closely related, as it's hard to imagine a language with first-class functions that would not also support higher-order functions, and conversely a language with higher-order functions but without first-class function support.

JavaScript Higher-order functions

These are functions that either accept a function as an argument or return a function when invoked. In other words, higher-order functions work with other functions. To understand this concept, you must think of JavaScript functions as values; functions are objects. We know that they can take values as input and return a value as output. Thus, a higher-order function is one where either an input or output value is a function. A higher-order function can both take a function as an argument and return a function.

What are the JavaScript Reference Values and where are they stored?

These mutable values are pieces of data that can be altered and are stored on the heap. When assigning a variable that has a reference value to another variable, you are assigning a reference to the value, kind of like copying the arrow that's pointing to the value and pasting that arrow to the other variable.

Consider the code below, and our desired output: let TESgames = { titles: ['Arena', 'Daggerfall', 'Morrowind', 'Oblivion', 'Skyrim'], seriesTitle: 'The Elder Scrolls', listGames( ) { this.titles.forEach(function(title) { console.log(this.seriesTitle + ' ' + title); }); } }; TESgames.listGames( ); Desired output: The Elder Scrolls Arena The Elder Scrolls Daggerfall The Elder Scrolls Morrowind The Elder Scrolls Oblivion The Elder Scrolls Skyrim Will this code log our desired output? Why or why not?

This code doesn't log our desired output, but instead logs this: undefined Arena undefined Daggerfall undefined Morrowind undefined Oblivion undefined Skyrim This happens because functions as arguments lose the surrounding context. In this case, the function expression invoked on each iteration of forEach inside of listGames loses TESgames as context. As a result, this on line 6 references the global object, and resolves to undefined rather than "The Elder Scrolls".

What does the code below do? function func( ) { b = 1; } func(); console.log(b);

This code logs 1. Unlike in the previous problem, we don't declare b; rather, we simply initialize it. As a result, b is created as a property on the global object, despite the fact that it's initialized in function scope.

JavaScript: concise property and concise method syntax

This code returns an object that has two properties: a bar property whose value is given by the bar parameter, and a qux property that defines a method. Modern JavaScript lets us simplify the text using the concise syntax.

In JavaScript, what values participate in garbage collection?

This question isn't as simple as it sounds; it depends on the different ways that programming languages define variables and where the language stores the values assigned to those variables. Most programming languages divide memory into two principal regions: the stack and the heap. JavaScript stores most primitive values as well as references on the stack, and everything else on the heap. You can think of references as pointers to the actual value of an object, array, or string that lives in the heap.

JavaScript: concise property syntax

Thus far, you've seen that we can use the following syntax to initialize object properties. That syntax is straightforward and easy to understand, but sometimes you need to initialize an object from a bunch of variables, often using the same name. That gets a little tedious and error-prone. ES6 introduced a new concise syntax that simplifies initializations of this nature. In each case, we merely use the name of the property we want to initialize, and JavaScript looks for a variable with the same name to use as the initial value. You can mix this concise notation with ordinary initializers. In this case, we create a property named answer for the qux variable.

Why use closures in JavaScript to make data private?

Using closures to restrict data access is a good way to force other developers to use the intended interface. By keeping the collection of items private, we enforce access via the provided methods. This restriction helps protect data integrity since developers must use the defined interface. In the makeList function case, data integrity isn't a big concern, but the code illustrates the point; you must use add to add an item to the list, which ensures that we log every addition. We'll see another example in the next assignment; there, we'll prevent unauthorized data modification. These benefits have a cost. For instance, making data private can make it harder to extend the code.

Node JS Module Scope

Variables in the module scope are those declared at the top level (not inside a function definition or object) of a node.js file. Consequently, module-scoped variables are not added to the global object, global (again window for browsers). Module-scoped variables are only accessible from within the file but not accessible anywhere else.

The pictured problem is an example of what?

We call this partial application: the original function already has some of its arguments defined. In effect, the program partially applies them ahead of time. Since you already have their values, you don't need to provide them when you invoke the function. Here, later partially applies functions that take a single argument. You can use partial application with functions that take any number of arguments; you can provide some arguments ahead of time, and provide the others when you invoke the returned function.

Dealing with Context Loss: Internal Function losing method context, Solution 4: Using an Arrow Function.

We can define bar using an arrow function since the value of this when using an arrow function is based on lexical scoping rules.

What function can we use to permanently bind a function to a particular execution context?

We can use the Function method bind to permanently bind a function to an execution context.

We decide that we want each invocation of foo.incrementA to increment foo.a by 3, rather than 1, and alter our code accordingly: let foo = { a: 0, incrementA( ) { function increment( ) { this.a += 1; } increment.apply(this); increment.apply(this); increment.apply(this); } }; Calling apply three times seems repetitive, though. Use bind to permanently set foo as increment's execution context.

We get to use Function.prototype.bind by changing the syntax for defining the increment function from a function declaration to a function expression. We then supply this as context, because this points to the object holding the method. bind can't be called on a function declaration, but can be called on a function expression.

What does this point to in the code below? function whatIsMyContext( ) { return this; }

We won't know the context of a function until execution time. Thus, we don't know what the context is here.

Our desired output for the code below is: Christopher Turk is a Surgeon. What will the code output, and what explains the difference, if any, between the actual and desired outputs? let turk = { firstName: 'Christopher', lastName: 'Turk', occupation: 'Surgeon', getDescription( ) { return this.firstName + ' ' + this.lastName + ' is a ' + this.occupation + '.'; } }; function logReturnVal(func) { let returnVal = func( ); console.log(returnVal); } logReturnVal(turk.getDescription);

When we extracted getDescription from turk and passed it into logReturnVal as an argument, we removed the method from its context. As a result, upon execution as func, this will point to the global object, rather than turk. Since Window doesn't have properties defined for firstName, lastName, or occupation, we get the output we do.

Gentle explanation of 'this' keyword in JavaScript: Because the function invocation has the biggest impart on this, from now on do not ask yourself:

Where is this taken from? but rather How is the function invoked? For an arrow function ask yourself: What is this where the arrow function is defined?

How does JavaScript implement it's bind function?

While you've learned enough to understand most of that code, it's not really important to wrap your head around it. What's important to recognize is that bind's context is the original function, and it returns a new function that calls the original function with the context supplied to bind as its first argument. This code also shows why the binding makes permanent changes -- no matter what you do to the returned function, you can't change the value of context.

In JavaScript, the behavior for the var variable appears to be identical to what happens when you don't declare the variable. There's a subtle but significant difference, what is it?

You can delete global variables that you don't declare, but not those that you did. It's as though JavaScript tries to hide the fact that var variables and functions are global object properties! There are times when this matters, so you should be familiar with the concept.

Dealing with Context Loss: Internal Function losing method context, Solution 2: Pass the context to internal functions.

You can pass the context object to the function with call or apply, as seen here on line 9.

Dealing with Context Loss: Function as Argument Losing Surrounding Context, Solution 2: Bind the argument function with the surrounding context.

You can use bind when you define the function to provide a permanent context to bar. Note that you must call bind with a function expression, not a function declaration; using bind with a function declaration results in an error.

Dealing with Context Loss: Internal Function losing method context, Solution 3: Bind the Context with a Function expression.

You can use bind when you define the function to provide a permanent context to bar. Note that you must call bind with a function expression, not a function declaration; using bind with a function declaration results in an error. One advantage of using bind is that you can do it once and then call it as often as you want without explicitly providing a context.

Given the following code: function startup( ) { let status = 'ready'; return function( ) { console.log('The system is ready.'); }; } let ready = startup( ); let systemStatus = // ? How can you set the value of systemStatus to the value of the inner variable status without changing startup in any way?

You can't do this. There is no way to access the value of the variable from outside the function. status is only available to the closure formed by the anonymous function returned by startup. This technique lets us define "private" variables.

Dealing with Context Loss: Internal Function losing method context.

Your instincts may tell you that this code will log "hello world" to the console. Your instincts are wrong here. Even though foo executes within the obj context, the call to bar on line 9 does not provide an explicit context, which means that JavaScript binds the global object to the function. As a result, this on line 6 is the global object, not obj. This trap is insidious and well-known. Most developers consider it to be a mistake in the language design. If we provide the context to call foo, then the context should propagate to its internal functions. It doesn't, though, and it's hard to imagine how binding the function to the global object is ever useful.

Given the pictured code and desired output shown, should you use call or apply to supply explicit context and the arguments to outputList? That is, which method makes the most sense to use? Implement a solution using your preferred method such that the desired output is logged, and explain your choice.

apply takes an array of arguments to be passed to the invoked function, rather than call's comma-separated arguments. Since the data we are concerned with (fruitsObj.list) is held in Array format, it makes more sense to use apply. outputList.apply(fruitsObj, fruitsObj.list); A more modern solution for this problem uses call and the new "spread syntax" touched on in our Syntactic Sugar gist: outputList.call(fruitsObj, ...fruitsObj.list);

What will the code below output? let obj = { a: 2, b: 3, }; function foo( ) { return this.a + this.b; } let bar = foo.bind(obj); console.log(bar( ));

bar is explicitly bound to obj on line 10, and as a result references that object's properties a and b when it is invoked.

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in a bound function?

this is the first argument of .bind() when invoking a bound function. The role of .bind() is to create a new function, which invocation will have the context as the first argument passed to .bind(). It is a powerful technique that allows to create functions with a predefined this value.

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in an indirect invocation?

this is the first argument of .call() or .apply() in an indirect invocation. It's obvious that this in indirect invocation is the value passed as first argument to .call() or .apply().

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in a function invocation? What about outside any function scope?

this is the global object in a function invocation. When this is used outside any function scope (the top most scope: global execution context), it also refers to the global object:

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in a constructor invocation?

this is the newly created object in a constructor invocation. The context of a constructor invocation is the newly created object. It is used to initialize the object with data that comes from constructor function arguments, setup initial value for properties, attach event handlers, etc.

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in a method invocation?

this is the object that owns the method in a method invocation. When invoking a method on an object, this becomes the object itself.

What will the code below output? let obj = { foo( ) { return this; }, }; let context = obj.foo( ); console.log(context); Explain the difference, if any, between the above output and that of the below: function foo( ) { return this; } let context = foo( ); console.log(context);

Unlike the bottom code, the top code outputs the object obj. This happens since foo is invoked as a method. Thus, its execution context refers to the object used to call the function.

Key JavaScript variable scoping rules.

- Every function declaration creates a new local variable scope. - Every block creates a new local variable scope. - Lexical scope uses the structure of the source code to determine the variable's scope. This means that the code doesn't have to be executed for the scope to exist. - All variables in the same or surrounding scopes are visible inside functions and blocks.

JavaScript, function objects using method and function invocation.

Function Objects can use both method and function invocations.

JavaScript Function Execution Context.

Every time a JavaScript function is invoked, it has access to an object called the execution context of that function. This execution context is accessible through the keyword this. A JavaScript function can be invoked in a variety of ways. Which object this refers to depends on how the function was invoked.

JavaScript call and apply methods mnemonic to help remember what each method does?

- Call: Count the Commas (you have to count the number of arguments to match the called function) - Apply: Arguments as Array

All functions, regardless of syntax, obey the same lexical scoping rules.

- They can access any variables defined within it. - They can access any variables that were in scope based on the context where the function was defined.

The object oriented code makes these questions easier to answer.

1.) What are the important concepts in the program? 2.) What are the properties of the object in question? 3.) How do we create said objects? 4.) What operations can I perform on said object? 5.) Where should we add new properties and methods?

Gentle explanation of 'this' keyword in JavaScript: Pitfall: this in an inner function

A common trap with the function invocation is thinking that this is the same in an inner function as in the outer function. The context of the inner function depends only on invocation, but not on the outer function's context. To have the expected this, modify the inner function's context with indirect invocation (using .call( ) or .apply( ), or create a bound function (using .bind( ).

Gentle explanation of 'this' keyword in JavaScript: What is a bound function?

A function connected with an object. Usually it is created from the original function using .bind() method. The original and bound functions share the same code and scope, but different contexts on execution. .bind() makes a permanent context link and will always keep it. A bound function cannot change its linked context when using .call() or .apply() with a different context, or even a rebound doesn't have any effect.

It's important to reiterate that implicit execution context is bound upon invocation, not definition.

Although bar begins its life as an object property, when it is invoked as a function (as it is after being assigned to baz) its context is bound to the global object.

JavaScript Functions as Object Factories.

An Object is a useful organizational tool that collects related data and behavior together. The benefits of this organization become evident when an application uses more than one instance of a given Object type. One way to clarify the differences between object instances in the code is to move the object similarities to one location while setting the differences when we define individual objects.

Dealing with Context Loss: Function as Argument Losing Surrounding Context, Solution 4: Use arrow function for the callback.

Arrow functions do not have a this binding. Instead of this being dependent on the location of the function invocation, JavaScript resolves it by looking at the enclosing scopes. this resolves to obj which is the immediately enclosing scope.

Gentle explanation of 'this' keyword in JavaScript: The context is also equivalent to.....?

Context of an invocation is the value of this within function body. For example the invocation of map.set('key', 'value') has the context map.

Why are JavaScript functions also called closures?

Functions close over or enclose the context at their definition point, so we call them closures. They always have access to that context, regardless of when and where the program invokes the function. function makeCounter( ) { let count = 0; // declare a new variable return function( ) { count += 1; // references count from the outer scope console.log(count); }; } Since makeCounter returns a function, we use it like this: > let counter = makeCounter( ); > counter( ); 1 > counter( ); 2 > counter( ); 3 Note that count is private data for the function returned by makeCounter. The closure makes it impossible to access the value of count from outside itself: let counter = makeCounter(); console.log(count); // ReferenceError: count is not defined console.log(counter.count); // undefined: Declarations inside closures aren't accessible from outside On the other hand, as we saw above, the function returned by makeCounter can freely access and update counter.

Gentle explanation of 'this' keyword in JavaScript: What is the key to understanding 'this' key word?

Having a clear view over function invocation and how it impacts the context.

Dealing with Context Loss: Function as Argument Losing Surrounding Context.

In the top example, we call repeatThreeTimes with a function argument that contains this. repeatThreeTimes calls its argument three times, but each time it does so without an explicit context. As we've learned, this means the context is the global object. Thus, this inside the function is the global object, not john. If you think that this problem happens infrequently, consider the bottom code. It looks simple enough; the code loops over an array and logs some information to the console. The problem, though, is that forEach executes the anonymous function passed to it, so it gets executed with the global object as context. Once again, this has the wrong value, and the function doesn't do what we want.

In JavaScript strict mode, what is the value of this in the global scope?

It's important to note that, in strict mode, this in the global scope is undefined.

JavaScript: Function vs. Method Invocation

JavaScript objects may contain methods among their properties. Object methods are properties that happen to have a Function value. You can think of methods as Functions with a receiver, which is the object the method is called on. If a call doesn't have an explicit receiver, it is a function. We call these two invocation forms "method invocation" and "function invocation," respectively.

JavaScript Prototypal Inheritance and Behavior Delegation

JavaScript's prototype chain lookup for properties gives us the ability to store an object's data and behaviors not just in the object itself, but anywhere on its prototype chain. This is very powerful when we want to share data or behaviors. We may have thousands (or more!) of dogs in our program, but instead of defining the say and run methods on every object, we defined those methods on dog, the prototype object of all dogs.

What does the code below do? "use strict" function func( ) { b = 1; } func(); console.log(b);

Line 4 raises a ReferenceError. In strict mode, we don't have access to the global object as the implicit execution context. Thus, all variables have to be first declared before being used.

Garbage Collection

Releases memory that was used for a variable's value once the variable is no longer to be used by a program. In JavaScript, values are allocated memory when they are created, and they are eventually, "automatically" freed up when they are not in use. This process of "automatically" freeing memory up is called garbage-collection. As developers, we don't often have to worry about managing memory, though we sometimes need to concern ourselves with how much memory we use. Programming languages that don't have garbage collection, GC for short, make the developer write code to deallocate (unclaim or release) memory when the program no longer needs the data. This process is messy and error-prone, and often leads to serious bugs and "memory leaks."

What will the code below log to the console? let positiveMentality = { message: 'JavaScript makes sense!', }; let negativeMentality = { message: 'JavaScript makes no sense!', }; function foo( ) { console.log(this.message); } let bar = foo.bind(positiveMentality); negativeMentality.logMessage = bar; negativeMentality.logMessage( );

Since bar is bound to positiveMentality as the return value of the bind invocation on line 13, positiveMentality's property message is logged by the function call on the last line, despite the fact that the function is invoked as a method on the negativeMentality object.

JavaScript call and apply methods.

The call method can also pass arguments to the function. List the arguments one by one after the context object. The apply method is identical to call, except that it uses an array to pass arguments.

JavaScript Implicit Function Execution Context?

The implicit function execution context (also called implicit binding for functions) is the context for a function that you invoke without supplying an explicit context. JavaScript binds such functions to the global object. The example makes sense. Back in the "Global Object" topic we learned that running foo() is like running window.foo(); the function's execution context is the global object, window.

JavaScript lexical scoping rules vs this binding.

The mechanics of how this binding works in JavaScript is an important but somewhat difficult concept. Some of this difficulty can arise from the tendency to apply lexical scoping rules to this binding. It's important to remember that the rules for this binding are entirely different than the rules for determining the scope of a variable. While variable scope is determined at the time of writing the code, this gets bound based on how a function is invoked.

What will the code below output? "use strict" function foo( ) { return this; } let context = foo( ); console.log(context);

The return value of foo is the global this, which is undefined in strict mode.

JavaScript: What is this during Method Invocation?

The value of this is a reference to the object itself. Within advance, this references the counter object. The function can use this to access and change the object's properties. Here, advance uses this to increment the count property in counter.

What are the JavaScript Primitive Values and where are they stored?

These immutable values are pieces of data that cannot be changed and they are stored in the stack. When assigning a variable that has a primitive value to another variable, you are assigning a copy of the value, kind of like copying and pasting it to the other variable.

Gentle explanation of 'this' keyword in JavaScript: Pitfall: forgetting about new

Using a function invocation to create objects is a potential problem (excluding factory pattern), because some constructors may omit the logic to initialize the object when new keyword is missing.

Dealing with Context Loss: Function as Argument Losing Surrounding Context, Solution 1: Use a local variable in the lexical scope to store this

let self = this or let that = this fix. You save this in a variable named self or that before calling the function, then reference the variable in the function.

Gentle explanation of 'this' keyword in JavaScript: Constructor Invocation

performed when new keyword is followed by an expression that evaluates to a function object, an open parenthesis (, a comma separated list of arguments expressions and a close parenthesis ). For example: new RegExp('\\d'). A constructor call creates an empty new object, which inherits properties from constructor's prototype. The role of constructor function is to initialize the object.

Gentle explanation of 'this' keyword in JavaScript: What is the value of this in an arrow function?

this is the enclosing context where the arrow function is defined. The arrow function doesn't create its own execution context, but takes this from the outer function where it is defined. An arrow function is bound with the lexical context once and forever. this cannot be modified even if using the context modification methods:


Conjuntos de estudio relacionados

Oxygenation & Perfusion - Multiple Choice Quiz

View Set

Legislative and Executive Test (MCQ)

View Set

WHOLE TEST answers and study guide

View Set

Foundations Chapter 3 - The World Marketplace

View Set

Perry chapter 31: SIDS and Immunizations

View Set

Chapter 9: Teaching and Counseling

View Set

Chapter 17: Death, Dying, and Grieving

View Set