From 608cd00e646e72615e042826b3e91fda3a18f81c Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Fri, 16 Feb 2024 08:23:10 -0500 Subject: [PATCH 01/32] Lint 'objects_and_object_constructors.md' --- .../objects_and_object_constructors.md | 55 +++++++++---------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index f5bc8a659a5..ff9ce9bda7d 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -2,7 +2,7 @@ In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. -There are multiple ways to define objects but in most cases, it is best to use the __object literal__ syntax as follows: +There are multiple ways to define objects but in most cases, it is best to use the **object literal** syntax as follows: ```javascript const myObject = { @@ -34,7 +34,7 @@ myObject.variable; // this gives us 'undefined' because it's looking for a prope myObject[variable]; // this is equivalent to myObject['property'] and returns 'Value!' ``` -If you are feeling rusty on using objects, now might be a good time to go back and review the content in [__Fundamentals 5__](https://www.theodinproject.com/lessons/foundations-fundamentals-part-5) from our JavaScript Basics course. +If you are feeling rusty on using objects, now might be a good time to go back and review the content in [**Fundamentals 5**](https://www.theodinproject.com/lessons/foundations-fundamentals-part-5) from our JavaScript Basics course. ### Lesson overview @@ -85,7 +85,7 @@ console.log(playerOneName); console.log(playerTwoName); ``` -Again, this isn't _that_ bad... but what if you _don't know_ which player's name you want to print? +Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print? ```javascript function gameOver(winningPlayer){ @@ -131,8 +131,6 @@ player1.sayName(); // logs 'steve' player2.sayName(); // logs 'also steve' ``` - - ### Exercise Write a constructor for making "Book" objects. We will revisit this in the project at the end of this lesson. Your book objects should have the book's `title`, `author`, the number of `pages`, and whether or not you have `read` the book. @@ -143,7 +141,7 @@ Put a function into the constructor that can report the book info like so: theHobbit.info(); // "The Hobbit by J.R.R. Tolkien, 295 pages, not read yet" ``` -Note: It is almost _always_ best to `return` things rather than putting `console.log()` directly into the function. In this case, return the `info` string and log it after the function has been called: +Note: It is almost *always* best to `return` things rather than putting `console.log()` directly into the function. In this case, return the `info` string and log it after the function has been called: ```javascript console.log(theHobbit.info()); @@ -151,7 +149,7 @@ console.log(theHobbit.info()); ### The prototype -Before we go much further, there's something important you need to understand about JavaScript objects. All objects in JavaScript have a `prototype`. The `prototype` is another object that the original object _inherits_ from, which is to say, the original object has access to all of its `prototype`'s methods and properties. +Before we go much further, there's something important you need to understand about JavaScript objects. All objects in JavaScript have a `prototype`. The `prototype` is another object that the original object *inherits* from, which is to say, the original object has access to all of its `prototype`'s methods and properties. Let's break it down. @@ -159,17 +157,17 @@ Let's break it down. Pretty straightforward sentence here! Every object in JavaScript has a `prototype`. So for example, the `player1` and `player2` objects from before, (created with the `Player(name, marker)` object constructor) also have a `prototype`. Now, what does having a `prototype` mean? What even is a `prototype` of an object? -#### 2. The prototype is another object... +#### 2. The prototype is another object -This sentence also seems pretty straightforward! The `prototype` _is just another object_ - again, like the `player1` and the `player2` objects. The `prototype` object can have properties and functions, just as these `Player` objects have properties like `.name`, `.marker`, and functions like `.sayName()` attached to them. +This sentence also seems pretty straightforward! The `prototype` *is just another object* - again, like the `player1` and the `player2` objects. The `prototype` object can have properties and functions, just as these `Player` objects have properties like `.name`, `.marker`, and functions like `.sayName()` attached to them. -#### 3. ...that the original object _inherits_ from, and has access to all of its prototype's methods and properties +#### 3. ...that the original object *inherits* from, and has access to all of its prototype's methods and properties Here, the "original object" refers to an object like `player1` or `player2`. These objects are said to "inherit", or in other words, these objects have access to the `prototype`'s properties or functions, if they have been defined. For example, if there was a `.sayHello()` function defined on the `prototype`, `player1` can access the function just as if it was its own function - `player1.sayHello()`. But it's not just `player1` who can call the `.sayHello()` function, even `player2` can call it, since it's defined on the `prototype`! Read on to know the details of how it works and how you could do this yourself! #### Accessing an object's prototype -Conceptually, you now might feel like you know, or at least have an idea of what a `prototype` of an object is. But how do you _know_ or actually _see_ what the prototype of an object is? Let's find out. You can try running the following code in the developer console of your browser. (Make sure you've created the `player1` and `player2` objects from before!) +Conceptually, you now might feel like you know, or at least have an idea of what a `prototype` of an object is. But how do you *know* or actually *see* what the prototype of an object is? Let's find out. You can try running the following code in the developer console of your browser. (Make sure you've created the `player1` and `player2` objects from before!) ```javascript Object.getPrototypeOf(player1) === Player.prototype; // returns true @@ -182,10 +180,10 @@ Now, to understand this code, let's use the three points from earlier: - You can check the object's `prototype` by using the [`Object.getPrototypeOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf) function on the object, like `Object.getPrototypeOf(player1)`. - The return value (result) of this function refers to the `.prototype` property of the Object Constructor (i.e., `Player(name, marker)`) - `Object.getPrototypeOf(player1) === Player.prototype`. 1. **The prototype is another object...** - - The _value_ of the Object Constructor's `.prototype` property (i.e., `Player.prototype`) contains the `prototype` object. - - The _reference_ to this value of `Player.prototype` is stored in every `Player` object, every time a `Player` object is created. + - The *value* of the Object Constructor's `.prototype` property (i.e., `Player.prototype`) contains the `prototype` object. + - The *reference* to this value of `Player.prototype` is stored in every `Player` object, every time a `Player` object is created. - Hence, you get a `true` value returned when you check the Objects prototype - `Object.getPrototypeOf(player1) === Player.prototype`. -1. **...that the original object _inherits_ from, and has access to all of its prototype's methods and properties**: +1. **...that the original object *inherits* from, and has access to all of its prototype's methods and properties**: - As said in the earlier point, every `Player` object has a value which refers to `Player.prototype`. So: `Object.getPrototypeOf(player1) === Object.getPrototypeOf(player2)` (returns `true`). - So, any properties or methods defined on `Player.prototype` will be available to the created `Player` objects! @@ -223,7 +221,7 @@ Now, you may also have a question - what use is an object's `prototype`? What is We can narrow it down to two reasons: 1. We can define properties and functions common among all objects on the `prototype` to save memory. Defining every property and function takes up a lot of memory, especially if you have a lot of common properties and functions, and a lot of created objects! Defining them on a centralized, shared object which the objects have access to, thus saves memory. -1. The second reason is the name of this section, **Prototypal Inheritance**, which we've referred to in passing earlier, in the introduction to the Prototype. In recap, we can say that the `player1` and `player2` objects _inherit_ from the `Player.prototype` object, which allows them to access functions like `.sayHello`. +1. The second reason is the name of this section, **Prototypal Inheritance**, which we've referred to in passing earlier, in the introduction to the Prototype. In recap, we can say that the `player1` and `player2` objects *inherit* from the `Player.prototype` object, which allows them to access functions like `.sayHello`. Let's now try to do the following: @@ -261,7 +259,7 @@ However, this chain does not go on forever, and if you have already tried loggin Note: 1. Every `prototype` object inherits from `Object.prototype` by default. -1. An object's `Object.getPrototypeOf()` value can only be _one_ unique `prototype` object. +1. An object's `Object.getPrototypeOf()` value can only be *one* unique `prototype` object. #### Recommended method for prototypal inheritance @@ -308,7 +306,7 @@ From the code, we can see that we've defined a `Person` from whom a `Player` inh Note: -Though it seems to be an easy way to set up Prototypal Inheritance using `Object.setPrototypeOf()`, the prototype chain has to be set up using this function _before_ creating any objects. Using `setPrototypeOf()` after objects have already been created can result in performance issues. +Though it seems to be an easy way to set up Prototypal Inheritance using `Object.setPrototypeOf()`, the prototype chain has to be set up using this function *before* creating any objects. Using `setPrototypeOf()` after objects have already been created can result in performance issues. A warning... this doesn't work: @@ -361,14 +359,15 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e 1. Read up on the concept of the prototype from the articles below. 1. Read the article [Understanding Prototypes and Inheritance in JavaScript](https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript) from Digital Ocean. This is a good review of prototype inheritance and constructor functions, featuring some examples. - 2. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. -2. You might have noticed us using the `this` keyword in object constructors and prototype methods in the examples above. - 1. [Dmitri Pavlutin's article on the `this` keyword](https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/) is very comprehensive and covers how `this` changes in various situations. You should have a solid understanding of the concept after reading it. Pay special attention to the pitfalls mentioned in each section. + 1. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. +1. You might have noticed us using the `this` keyword in object constructors and prototype methods in the examples above. + 1. [Dmitri Pavlutin's article](https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/) on the `this` keyword is very comprehensive and covers how `this` changes in various situations. You should have a solid understanding of the concept after reading it. Pay special attention to the pitfalls mentioned in each section. + ### Knowledge check -This section contains questions for you to check your understanding of this lesson. If you’re having trouble answering the questions below on your own, review the material above to find the answer. +The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge. - [Write an object constructor and instantiate the object.](#object-constructors) - [Describe what a prototype is and how it can be used.](#the-prototype) @@ -379,14 +378,14 @@ This section contains questions for you to check your understanding of this less ### Additional resources -This section contains helpful links to other content. It isn't required, so consider it supplemental. +This section contains helpful links to related content. It isn't required, so consider it supplemental. -- [This article](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co) from Lydia Hallie and [This video](https://www.youtube.com/watch?v=sOrtAjyk4lQ) from Avelx explains the Prototype concept with graphics and beginner friendly language. Try using these resources if you want another perspective to understand the concept. -- [This video](https://www.youtube.com/watch?v=CDFN1VatiJA) from mpj explains `Object.create` method with great details about it, he walks through what it is, why `Object.create` exists in JavaScript, and how to use `Object.create`. Also you can check [This video](https://www.youtube.com/watch?v=MACDGu96wrA) from techsith to understand another point of view of extending objects from others by `Object.create`. +- [Lydia Hallie's article](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co) and [Avelx' video](https://www.youtube.com/watch?v=sOrtAjyk4lQ) explains the Prototype concept with graphics and beginner friendly language. Try using these resources if you want another perspective to understand the concept. +- [mpj's video](https://www.youtube.com/watch?v=CDFN1VatiJA) explains `Object.create` method with great details about it, he walks through what it is, why `Object.create` exists in JavaScript, and how to use `Object.create`. Also you can check [techsith's video](https://www.youtube.com/watch?v=MACDGu96wrA) to understand another point of view of extending objects from others by `Object.create`. - [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by -Nicholas C. Zakas is really great to understand OOP in javascript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. -- [This stack overflow question](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) explains the difference between defining methods via the prototype vs defining them in the constructor. +Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. +- This [stack overflow question](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) explains the difference between defining methods via the prototype vs defining them in the constructor. - [A Beginner’s Guide to JavaScript’s Prototype](https://medium.com/free-code-camp/a-beginners-guide-to-javascript-s-prototype-9c049fe7b34) and [JavaScript Inheritance and the Prototype Chain](https://medium.com/free-code-camp/javascript-inheritance-and-the-prototype-chain-d4298619bdae) from Tyler Mcginnis has great examples to help you understand Prototype and Prototype Chain better from the beginner's perspective. -- [This video ](https://www.youtube.com/watch?v=wstwjQ1yqWQ) from Akshay Saini is an easy way to understand the concept of Prototype, Prototype Chain and prototypal inheritance. +- [Akshay Saini's video](https://www.youtube.com/watch?v=wstwjQ1yqWQ) is an easy way to understand the concept of Prototype, Prototype Chain and prototypal inheritance. - [Interactive Scrim on objects and object constructors.](https://scrimba.com/scrim/co2624f87981575448091d5a2) -- [Check out this video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. +- Check out this [video explanation on the `this` keyword](https://www.youtube.com/watch?v=cwChC4BQF0Q) from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. From e3e36f90089fd34200d3a1f9ef175b6858ab3ac2 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Fri, 16 Feb 2024 09:04:17 -0500 Subject: [PATCH 02/32] Add examples of how objects are useful both to organize data and to group functionality --- .../objects_and_object_constructors.md | 133 +++++++++++++++--- 1 file changed, 113 insertions(+), 20 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index ff9ce9bda7d..d13ad53701c 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -40,18 +40,20 @@ If you are feeling rusty on using objects, now might be a good time to go back a This section contains a general overview of topics that you will learn in this lesson. +- Explain how objects can be used to organize data +- Explain how objects can be used to organize functionality +- Explain what the `this` keyword is. - How to write an object constructor and instantiate the object. - Describe what a prototype is and how it can be used. - Explain prototypal inheritance. - Understand the basic do's and don't's of prototypal inheritance. - Explain what `Object.create` does. -- Explain what the `this` keyword is. -### Objects as a design pattern +### Objects as a data structure -One of the simplest ways you can begin to organize your code is by grouping things into objects. Take these examples from a 'tic tac toe' game: +You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: -```javascript +```js // example one const playerOneName = "tim"; const playerTwoName = "jenn"; @@ -60,45 +62,135 @@ const playerTwoMarker = "O"; // example two const playerOne = { -  name: "tim", -  marker: "X" + name: "tim", + marker: "X" }; const playerTwo = { -  name: "jenn", -  marker: "O" + name: "jenn", + marker: "O" }; ``` -At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Let me demonstrate: +At first glance, the first doesn’t seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate: -```javascript +```js function printName(player) { -  console.log(player.name); + console.log(player.name); } ``` -This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually `console.log` it: +This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player’s name, you would have to remember the correct variable name and then manually console.log it: -```javascript +```js console.log(playerOneName); console.log(playerTwoName); ``` -Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print? +Again, this isn’t that bad… but what if you don’t know which player’s name you want to print? -```javascript +```js function gameOver(winningPlayer){ -  console.log("Congratulations!"); -  console.log(winningPlayer.name + " is the winner!"); + console.log("Congratulations!"); + console.log(winningPlayer.name + " is the winner!"); } ``` -Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of an item's name, price, description and other things is the only way to go. Unfortunately, in that type of situation, manually typing out the contents of our objects is not feasible either. We need a cleaner way to create our objects, which brings us to... +Or, what if we aren’t making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item’s name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum. + +### Objects as a design pattern + +The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! + +One of the easiest ways to do this is to add ***methods*** to your objects in conjunction with JavaScript's `this` keyword. + +- A 'method' is just a fancy word for "a function that exists as a property of an object". +- The `this` keyword is used to refer to an object a particular method is called from. + +Let's take a look at a basic example of adding some functionality to one of our player objects: + +```js +const playerOne = { + name: "tim", + marker: "X", + + // special, shorthand syntax for adding methods in object literals + greet() { + console.log("Hi, I'm " + this.name + '!') + } +} + +playerOne.greet() // logs "Hi, I'm tim!" to the console +``` + +Our `greet()` method here uses the `this` keyword to look at it's parent object (`playerOne`), grab it's `name` property, then log that property to the console as a greeting. + +While that worked as a great example, this method isn't all that useful. Let's take this idea further and organize related code for the logic of a Rock Paper Scissors game into an object. + +Feel encouraged to copy this code into the developer console and experiment with how it works yourself! + +```js +const rps = { + _options: ['rock', 'paper', 'scissors'], + _getRandomChoice() { + const randomIndex = Math.floor(Math.random() * 3) + return this._options[randomIndex] + }, + _isTie(playerChoice, computerChoice) {return playerChoice === computerChoice}, + _isPlayerWinner(playerChoice, computerChoice) { + if( + (playerChoice === 'rock' && computerChoice === 'scissors') || + (playerChoice === 'paper' && computerChoice === 'rock') || + (playerChoice === 'scissors' && computerChoice === 'paper') + ) { + return true + } else { + return false + } + }, + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + // if an invalid choice is chosen, throw an error + if(!this._options.includes(playerChoice)) { + throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) + } + + // get the computer's choice + const computerChoice = this._getRandomChoice() + + // determine the winner, apply points if necessary, and return who won + if(this._isTie(playerChoice, computerChoice)) { + return "tie" + } else if(this._isPlayerWinner(playerChoice, computerChoice)) { + this.playerScore++ + return "player" + } else { + this.computerScore++ + return 'computer' + } + }, + reset() { + this.playerScore = 0; + this.computerScore = 0; + } +} + +rps.playRound('rock') // if we win a round, this function will return `'player'`... +rps.playerScore // ...and our score will be incremented to `1` +``` + +Now, everything you need to play this game is oraganized and conveniantly available within this one `rps` object. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. + +You may be wondering why some of the properties/methods of this object are prefixed by an underscore (`_`). This is just a convention to say "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". + +These methods might also be called "private methods"/"private properties", and even though **object literal** syntax doesn't provide a way to truly make them private, you will learn about other methods of creating objects that *can*. + +Private properties aren't stricly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, protect certain properties from being modified in ways that you may not have intended. ### Object constructors -When you have a specific type of object that you need to duplicate like our player or inventory items, a better way to create them is using an object constructor, which is a function that looks like this: +Manually typing out the contents of our objects with Object Literals is not always feasable. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: ```javascript function Player(name, marker) { @@ -369,6 +461,7 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge. +- [Explain two ways you can use objects to organize code.](#objects-as-a-data-structure) - [Write an object constructor and instantiate the object.](#object-constructors) - [Describe what a prototype is and how it can be used.](#the-prototype) - [Explain prototypal inheritance.](https://javascript.info/prototype-inheritance) @@ -381,7 +474,7 @@ The following questions are an opportunity to reflect on key topics in this less This section contains helpful links to related content. It isn't required, so consider it supplemental. - [Lydia Hallie's article](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co) and [Avelx' video](https://www.youtube.com/watch?v=sOrtAjyk4lQ) explains the Prototype concept with graphics and beginner friendly language. Try using these resources if you want another perspective to understand the concept. -- [mpj's video](https://www.youtube.com/watch?v=CDFN1VatiJA) explains `Object.create` method with great details about it, he walks through what it is, why `Object.create` exists in JavaScript, and how to use `Object.create`. Also you can check [techsith's video](https://www.youtube.com/watch?v=MACDGu96wrA) to understand another point of view of extending objects from others by `Object.create`. +- [mpj's video](https://www.youtube.com/watch?v=CDFN1VatiJA) explains the `Object.create` method with great details about it, he walks through what it is, why `Object.create` exists in JavaScript, and how to use `Object.create`. Also you can check [techsith's video](https://www.youtube.com/watch?v=MACDGu96wrA) to understand another point of view of extending objects from others by `Object.create`. - [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. - This [stack overflow question](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) explains the difference between defining methods via the prototype vs defining them in the constructor. From 77d0a710fa5866bd71d0de32a9842fad5c3b04d7 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Fri, 16 Feb 2024 11:28:24 -0500 Subject: [PATCH 03/32] Fix spelling errors --- .../objects_and_object_constructors.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index d13ad53701c..a4fc4530cee 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -180,17 +180,17 @@ rps.playRound('rock') // if we win a round, this function will return `'player'` rps.playerScore // ...and our score will be incremented to `1` ``` -Now, everything you need to play this game is oraganized and conveniantly available within this one `rps` object. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. +Now, everything you need to play this game is oraganized and conveniently available within this one `rps` object. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. You may be wondering why some of the properties/methods of this object are prefixed by an underscore (`_`). This is just a convention to say "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". These methods might also be called "private methods"/"private properties", and even though **object literal** syntax doesn't provide a way to truly make them private, you will learn about other methods of creating objects that *can*. -Private properties aren't stricly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, protect certain properties from being modified in ways that you may not have intended. +Private properties aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, protect certain properties from being modified in ways that you may not have intended. ### Object constructors -Manually typing out the contents of our objects with Object Literals is not always feasable. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: +Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: ```javascript function Player(name, marker) { @@ -473,7 +473,7 @@ The following questions are an opportunity to reflect on key topics in this less This section contains helpful links to related content. It isn't required, so consider it supplemental. -- [Lydia Hallie's article](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co) and [Avelx' video](https://www.youtube.com/watch?v=sOrtAjyk4lQ) explains the Prototype concept with graphics and beginner friendly language. Try using these resources if you want another perspective to understand the concept. +- [Lydia Hallie's article](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co) and [Avelx's video](https://www.youtube.com/watch?v=sOrtAjyk4lQ) explains the Prototype concept with graphics and beginner friendly language. Try using these resources if you want another perspective to understand the concept. - [mpj's video](https://www.youtube.com/watch?v=CDFN1VatiJA) explains the `Object.create` method with great details about it, he walks through what it is, why `Object.create` exists in JavaScript, and how to use `Object.create`. Also you can check [techsith's video](https://www.youtube.com/watch?v=MACDGu96wrA) to understand another point of view of extending objects from others by `Object.create`. - [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. From d6366b57dad281f824f4693e6accb2bc2ca1c5d2 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sun, 18 Feb 2024 06:09:10 -0500 Subject: [PATCH 04/32] Add additional examples of objects as a design pattern --- .../objects_and_object_constructors.md | 157 +++++++++++++++--- 1 file changed, 135 insertions(+), 22 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index a4fc4530cee..eb9e6b2b75c 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -100,34 +100,134 @@ Or, what if we aren’t making a 2 player game, but something more complicated s ### Objects as a design pattern -The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! +The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). -One of the easiest ways to do this is to add ***methods*** to your objects in conjunction with JavaScript's `this` keyword. +The inroductory paragraph for Object Oriented Programming on Wikipedia says this: -- A 'method' is just a fancy word for "a function that exists as a property of an object". -- The `this` keyword is used to refer to an object a particular method is called from. +> Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another. -Let's take a look at a basic example of adding some functionality to one of our player objects: +Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions on an object) that interact with that data. + +Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributtes of a *thing* are expressed as properties, and the ways you can interact with a thing are expressed as methods. + +Let's take an example a thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: ```js -const playerOne = { - name: "tim", - marker: "X", +const lightbulb = { + lightColor: 'fluorescent white', // this lightbulb is white, + lit: false // and is currently 'off' +} +``` + +You may want to have the ability to switch a lightbulb to on from it's unlit state, or vice-versa. To do that, you might add methods to these objects to do that. + +The easiest way to get started using methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from. + +The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`: + +```js +const lightbulb = { + lightColor: 'fluorescent white', + lit: false, + + // shorthand syntax for adding methods to objects + switchOn() { + // return false to indicate the light was already on + if(this.lit === true) return false + + // return true if the state of the light changed to be on + this.lit = true + return true + }, + switchOff() { + // return true if the state of the light changed to be off + if (this.lit === false) return false + this.lit = false + + // return false to indicate the light was already off + return true + } +} + +lightbulb.switchOn() // true - we switched it on +lightbulb.lit // true - the object has changed to reflect that! +``` + +These methods use the `this` keyword to refer to the object they get called from. The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other object. + +Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much. + +Moving past physical objects, we could also try to describe something like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. + +A rock paper scissors game might involve a few things: + +- Properties that keep track of players' scores +- A method that allows you to play a round with a computer player +- A method that allows you to reset the game might also be a useful way to interact with the object. + +So, at it's most basic, an object that represents the game might look something like this: + +```js +const rps = { + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + // code to play the round... + } +} +``` + +If we wanted our game object to automatically keep score for us as we played the game, we might flesh this code out to look something like this: + +```js +const rps = { + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + const options = ['rock', 'paper', 'scissors'] + + // if an invalid choice is chosen, throw an error + if(!options.includes(playerChoice.toLowerCase())) { + throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) + } + + // get the computer's choice + const computerChoice = options[Math.floor(Math.random() * 3)] + - // special, shorthand syntax for adding methods in object literals - greet() { - console.log("Hi, I'm " + this.name + '!') + // determine the winner, apply points if necessary, and return who won + if(playerChoice.toLowerCase() === computerChoice) { + return "tie" + } else if( + (playerChoice === 'rock' && computerChoice === 'scissors') || + (playerChoice === 'paper' && computerChoice === 'rock') || + (playerChoice === 'scissors' && computerChoice === 'paper') + ) { + this.playerScore++ + return "player" + } else { + this.computerScore++ + return 'computer' + } + }, + reset() { + this.playerScore = 0; + this.computerScore = 0; } } -playerOne.greet() // logs "Hi, I'm tim!" to the console +rps.playRound('rock') // returns 'player' if we win... +rps.playerScore // ...and our score would have increased + +// We also have the ability to reset the game at any time +rps.reset() ``` -Our `greet()` method here uses the `this` keyword to look at it's parent object (`playerOne`), grab it's `name` property, then log that property to the console as a greeting. +You may be looking at this code and thinking that you personally prefer to split your code between more functions than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object. -While that worked as a great example, this method isn't all that useful. Let's take this idea further and organize related code for the logic of a Rock Paper Scissors game into an object. +But, there is no rule saying that you can't add those functions to your object as well! A common convention is to prefix methods and properties that you don't intend other people to use with an underscore (`_`). This convention conveys to others that "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". -Feel encouraged to copy this code into the developer console and experiment with how it works yourself! +Let's see what that looks like! ```js const rps = { @@ -175,18 +275,29 @@ const rps = { this.computerScore = 0; } } - -rps.playRound('rock') // if we win a round, this function will return `'player'`... -rps.playerScore // ...and our score will be incremented to `1` ``` -Now, everything you need to play this game is oraganized and conveniently available within this one `rps` object. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. +Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly make them private, you will later learn about other methods of creating objects that *can*. + +Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties from being modified in ways that you may not have intended. + +The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future (we'll touch on this later, when we talk about object inheritance). + +This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. + +Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have a website where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects! + +
+ +#### Objects As Machines + +When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine each object as a little 'machine' you're making out of code that does something useful. -You may be wondering why some of the properties/methods of this object are prefixed by an underscore (`_`). This is just a convention to say "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". +The properties of the object might have basic information about your machine (like it's color), and additional information about it's current 'state', such as if the machine is currently on or off, what the machine has counted for a player's score, or how many coins havebeen inserted into your machine. -These methods might also be called "private methods"/"private properties", and even though **object literal** syntax doesn't provide a way to truly make them private, you will learn about other methods of creating objects that *can*. +The buttons and and such that make your machine do specific things would be represented by the the objects methods. A method might turn your machine from on 'on' to 'off', allow you to input information to play a game, or give the machine a coin so it can keep running (maybe your object represents an arcade game!). -Private properties aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, protect certain properties from being modified in ways that you may not have intended. +Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. ### Object constructors @@ -462,6 +573,8 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge. - [Explain two ways you can use objects to organize code.](#objects-as-a-data-structure) +- [What is a 'method'](#objects-as-a-design-pattern) +- [What is the `this` keyword used for?](#objects-as-a-design-pattern) - [Write an object constructor and instantiate the object.](#object-constructors) - [Describe what a prototype is and how it can be used.](#the-prototype) - [Explain prototypal inheritance.](https://javascript.info/prototype-inheritance) From 098d45149269d5e775372e763d41f25a32b0f0c3 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sun, 18 Feb 2024 06:15:57 -0500 Subject: [PATCH 05/32] fix never-ending note --- .../objects_and_object_constructors.md | 1 + 1 file changed, 1 insertion(+) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index eb9e6b2b75c..d37d9812336 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -299,6 +299,7 @@ The buttons and and such that make your machine do specific things would be repr Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. +
### Object constructors Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: From 9b9e4a16e0161d15b1071df5098ce55efa1f81ab Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sun, 18 Feb 2024 09:54:55 -0500 Subject: [PATCH 06/32] small editorial changes --- .../objects_and_object_constructors.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index d37d9812336..7e9d80f81c8 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -108,9 +108,9 @@ The inroductory paragraph for Object Oriented Programming on Wikipedia says this Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions on an object) that interact with that data. -Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributtes of a *thing* are expressed as properties, and the ways you can interact with a thing are expressed as methods. +Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. -Let's take an example a thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: +Let's take an example of some thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: ```js const lightbulb = { @@ -119,9 +119,9 @@ const lightbulb = { } ``` -You may want to have the ability to switch a lightbulb to on from it's unlit state, or vice-versa. To do that, you might add methods to these objects to do that. +You may want to have the ability to switch a lightbulb from it's unlit state to it's lit state, or vice-versa. To do that, you might add a *method*. -The easiest way to get started using methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from. +The easiest way to get started creating methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from. The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`: @@ -142,9 +142,9 @@ const lightbulb = { switchOff() { // return true if the state of the light changed to be off if (this.lit === false) return false - this.lit = false // return false to indicate the light was already off + this.lit = false return true } } @@ -153,7 +153,7 @@ lightbulb.switchOn() // true - we switched it on lightbulb.lit // true - the object has changed to reflect that! ``` -These methods use the `this` keyword to refer to the object they get called from. The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other object. +These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object. Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much. @@ -279,9 +279,9 @@ const rps = { Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly make them private, you will later learn about other methods of creating objects that *can*. -Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties from being modified in ways that you may not have intended. +Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! -The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future (we'll touch on this later, when we talk about object inheritance). +The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. @@ -300,6 +300,7 @@ The buttons and and such that make your machine do specific things would be repr Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. + ### Object constructors Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: From 4e581eae463a8336e9e1975a31197dd8daeb95f3 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sun, 18 Feb 2024 09:57:12 -0500 Subject: [PATCH 07/32] update language to fit the topic of objects representing more abstract things --- .../objects_and_object_constructors.md | 47 ++++++++++++++----- 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 7e9d80f81c8..2108e5ed3a5 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -159,25 +159,29 @@ Feel free to copy this code in the console and experiment with it! If you're inc Moving past physical objects, we could also try to describe something like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. -A rock paper scissors game might involve a few things: +A rock paper scissors game might involve a couple basic things: -- Properties that keep track of players' scores -- A method that allows you to play a round with a computer player -- A method that allows you to reset the game might also be a useful way to interact with the object. +- Players' scores +- The ability to play a round (and playing a round should update a player's score) -So, at it's most basic, an object that represents the game might look something like this: +And might also include a couple nice-to-haves + +- The ability to determine the current winning player +- The ability to restart the game + +So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a comuter player): ```js const rps = { playerScore: 0, computerScore: 0, playRound(playerChoice) { - // code to play the round... + // code to play the round... (and update the scores when a player wins) } } ``` -If we wanted our game object to automatically keep score for us as we played the game, we might flesh this code out to look something like this: +And if we fleshed it out, our object may come out to look something like this: ```js const rps = { @@ -210,6 +214,15 @@ const rps = { return 'computer' } }, + getWinningPlayer() { + if(this.playerScore === this.computerScore) { + return 'tie' + } else if (this.playerScore > this.computerScore) { + return 'player' + } else { + return 'computer' + } + }, reset() { this.playerScore = 0; this.computerScore = 0; @@ -219,8 +232,9 @@ const rps = { rps.playRound('rock') // returns 'player' if we win... rps.playerScore // ...and our score would have increased -// We also have the ability to reset the game at any time -rps.reset() +// We also have the ability to check the winner and reset the game at any time +rps.getWinningPlayer() // 'player', if we won above round +rps.reset() ``` You may be looking at this code and thinking that you personally prefer to split your code between more functions than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object. @@ -270,6 +284,15 @@ const rps = { return 'computer' } }, + getWinningPlayer() { + if(this.playerScore === this.computerScore) { + return 'tie' + } else if (this.playerScore > this.computerScore) { + return 'player' + } else { + return 'computer' + } + }, reset() { this.playerScore = 0; this.computerScore = 0; @@ -291,11 +314,11 @@ Furthermore, with the various object creation methods you'll learn throughout th #### Objects As Machines -When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine each object as a little 'machine' you're making out of code that does something useful. +When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine the object as a little 'machine' you're making out of code that does something useful. -The properties of the object might have basic information about your machine (like it's color), and additional information about it's current 'state', such as if the machine is currently on or off, what the machine has counted for a player's score, or how many coins havebeen inserted into your machine. +The properties of the machine could be thought of displays that might show information it's collected or been given to it so far, if it can currently be interacted with, what the machine has counted for a player's score... or about a billion other things, depending on what your object does. -The buttons and and such that make your machine do specific things would be represented by the the objects methods. A method might turn your machine from on 'on' to 'off', allow you to input information to play a game, or give the machine a coin so it can keep running (maybe your object represents an arcade game!). +The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing. A method might give your object new information to store in some way, turn your machine from on 'on' to 'off', allow you to input information to play a game, or switch between the turns of two different players. Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. From 827614de4ec7299d1d12d127d0aac04ceec5e639 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sat, 9 Mar 2024 17:25:57 -0500 Subject: [PATCH 08/32] fix code tags, apostrophes, and spelling errors --- .../objects_and_object_constructors.md | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 34ffcb1d15e..a364e3ebd88 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -52,7 +52,7 @@ This section contains a general overview of topics that you will learn in this l You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: -```js +```javascript // example one const playerOneName = "tim"; const playerTwoName = "jenn"; @@ -71,31 +71,31 @@ const playerTwo = { }; ``` -At first glance, the first doesn’t seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate: +At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate: -```js +```javascript function printName(player) { console.log(player.name); } ``` -This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player’s name, you would have to remember the correct variable name and then manually console.log it: +This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually console.log it: -```js +```javascript console.log(playerOneName); console.log(playerTwoName); ``` Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print? -```js +```javascript function gameOver(winningPlayer){ console.log("Congratulations!"); console.log(winningPlayer.name + " is the winner!"); } ``` -Or, what if we aren’t making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item’s name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum. +Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum. ### Objects as a design pattern @@ -111,7 +111,7 @@ Nearly *anything* you can think about can be described as an object. To do so, a Let's take an example of some thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: -```js +```javascript const lightbulb = { lightColor: 'fluorescent white', // this lightbulb is white, lit: false // and is currently 'off' @@ -124,7 +124,7 @@ The easiest way to get started creating methods to interact with your objects mi The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`: -```js +```javascript const lightbulb = { lightColor: 'fluorescent white', lit: false, @@ -168,9 +168,9 @@ And might also include a couple nice-to-haves - The ability to determine the current winning player - The ability to restart the game -So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a comuter player): +So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a computer player): -```js +```javascript const rps = { playerScore: 0, computerScore: 0, @@ -182,7 +182,7 @@ const rps = { And if we fleshed it out, our object may come out to look something like this: -```js +```javascript const rps = { playerScore: 0, computerScore: 0, @@ -242,7 +242,7 @@ But, there is no rule saying that you can't add those functions to your object a Let's see what that looks like! -```js +```javascript const rps = { _options: ['rock', 'paper', 'scissors'], _getRandomChoice() { @@ -611,7 +611,7 @@ This section contains helpful links to related content. It isn't required, so co - [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. - The first answer on this StackOverflow question regarding [defining methods via the prototype vs in the constructor](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) helps explain when you might want to use one over the other. -- [A Beginner’s Guide to JavaScript’s Prototype](https://medium.com/free-code-camp/a-beginners-guide-to-javascript-s-prototype-9c049fe7b34) and [JavaScript Inheritance and the Prototype Chain](https://medium.com/free-code-camp/javascript-inheritance-and-the-prototype-chain-d4298619bdae) from Tyler Mcginnis has great examples to help you understand Prototype and Prototype Chain better from the beginner's perspective. +- [A Beginner's Guide to JavaScript's Prototype](https://medium.com/free-code-camp/a-beginners-guide-to-javascript-s-prototype-9c049fe7b34) and [JavaScript Inheritance and the Prototype Chain](https://medium.com/free-code-camp/javascript-inheritance-and-the-prototype-chain-d4298619bdae) from Tyler Mcginnis has great examples to help you understand Prototype and Prototype Chain better from the beginner's perspective. - This video from Akshay Saini is an easy way to understand the [concept of Prototype, Prototype Chain and prototypal inheritance.](https://www.youtube.com/watch?v=wstwjQ1yqWQ). - [Interactive Scrim on objects and object constructors.](https://scrimba.com/scrim/co2624f87981575448091d5a2) - Check out this video explanation on the [`this` keyword from DevSage](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. From 9cb829e0d9879be570e56d120cd2c0058ad2df0b Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sat, 9 Mar 2024 18:49:47 -0500 Subject: [PATCH 09/32] remove unnecessary switchOn/switchOff logic --- .../objects_and_object_constructors.md | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index a364e3ebd88..af7bf92e65f 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -131,25 +131,15 @@ const lightbulb = { // shorthand syntax for adding methods to objects switchOn() { - // return false to indicate the light was already on - if(this.lit === true) return false - - // return true if the state of the light changed to be on this.lit = true - return true }, switchOff() { - // return true if the state of the light changed to be off - if (this.lit === false) return false - - // return false to indicate the light was already off this.lit = false - return true } } -lightbulb.switchOn() // true - we switched it on -lightbulb.lit // true - the object has changed to reflect that! +lightbulb.switchOn() +lightbulb.lit // true - we switched it on ``` These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object. From b78f8211d8c7c80d71ff367b137e075b41c60d3b Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Mon, 1 Jul 2024 10:55:35 -0400 Subject: [PATCH 10/32] add a new lesson on organizing code with objects --- .../organizing_code_with_objects.md | 336 ++++++++++++++++++ 1 file changed, 336 insertions(+) create mode 100644 javascript/organizing_your_javascript_code/organizing_code_with_objects.md diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md new file mode 100644 index 00000000000..ff34f296b0e --- /dev/null +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -0,0 +1,336 @@ +### Introduction + +In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. + +There are multiple ways to define objects but in most cases, it is best to use the **object literal** syntax as follows: + +```javascript +const myObject = { +  property: 'Value!', +  otherProperty: 77, +  "obnoxious property": function() { +    // do stuff! +  } +}; +``` + +There are also 2 ways to get information out of an object: dot notation and bracket notation. + +```javascript +// dot notation +myObject.property; // 'Value!' + +// bracket notation +myObject["obnoxious property"]; // [Function] +``` + +Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you cannot use variables in dot notation: + +```javascript +const variable = 'property'; + +myObject.variable; // this gives us 'undefined' because it's looking for a property named 'variable' in our object + +myObject[variable]; // this is equivalent to myObject['property'] and returns 'Value!' +``` + +If you are feeling rusty on using objects, now might be a good time to go back and review the content in our [object basics lesson](https://www.theodinproject.com/lessons/foundations-object-basics) from our JavaScript Basics course. + +### Lesson overview + +This section contains a general overview of topics that you will learn in this lesson. + +- Using objects to organize data. +- Using objects to organize functionality. +- Object methods and the `this` keyword +- Public and private interfaces + +### Objects as a data structure + +You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: + +```javascript +// example one +const playerOneName = "tim"; +const playerTwoName = "jenn"; +const playerOneMarker = "X"; +const playerTwoMarker = "O"; + +// example two +const playerOne = { + name: "tim", + marker: "X" +}; + +const playerTwo = { + name: "jenn", + marker: "O" +}; +``` + +At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate: + +```javascript +function printName(player) { + console.log(player.name); +} +``` + +This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually console.log it: + +```javascript +console.log(playerOneName); +console.log(playerTwoName); +``` + +Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print? + +```javascript +function gameOver(winningPlayer){ + console.log("Congratulations!"); + console.log(winningPlayer.name + " is the winner!"); +} +``` + +Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum. + +### Objects as a design pattern + +The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). + +The inroductory paragraph for Object Oriented Programming on Wikipedia says this: + +> Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another. + +Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions on an object) that interact with that data. + +Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. + +Let's take an example of some thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: + +```javascript +const lightbulb = { + lightColor: 'fluorescent white', // this lightbulb is white, + lit: false // and is currently 'off' +} +``` + +You may want to have the ability to switch a lightbulb from it's unlit state to it's lit state, or vice-versa. To do that, you might add a *method*. + +The easiest way to get started creating methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from. + +The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`: + +```javascript +const lightbulb = { + lightColor: 'fluorescent white', + lit: false, + + // shorthand syntax for adding methods to objects + switchOn() { + this.lit = true + }, + switchOff() { + this.lit = false + } +} + +lightbulb.switchOn() +lightbulb.lit // true - we switched it on +``` + +These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object. + +Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much. + +Moving past physical objects, we could also try to describe something like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. + +A rock paper scissors game might involve a couple basic things: + +- Players' scores +- The ability to play a round (and playing a round should update a player's score) + +And might also include a couple nice-to-haves + +- The ability to determine the current winning player +- The ability to restart the game + +So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a computer player): + +```javascript +const rps = { + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + // code to play the round... (and update the scores when a player wins) + } +} +``` + +And if we fleshed it out, our object may come out to look something like this: + +```javascript +const rps = { + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + const options = ['rock', 'paper', 'scissors'] + + // if an invalid choice is chosen, throw an error + if(!options.includes(playerChoice.toLowerCase())) { + throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) + } + + // get the computer's choice + const computerChoice = options[Math.floor(Math.random() * 3)] + + + // determine the winner, apply points if necessary, and return who won + if(playerChoice.toLowerCase() === computerChoice) { + return "tie" + } else if( + (playerChoice === 'rock' && computerChoice === 'scissors') || + (playerChoice === 'paper' && computerChoice === 'rock') || + (playerChoice === 'scissors' && computerChoice === 'paper') + ) { + this.playerScore++ + return "player" + } else { + this.computerScore++ + return 'computer' + } + }, + getWinningPlayer() { + if(this.playerScore === this.computerScore) { + return 'tie' + } else if (this.playerScore > this.computerScore) { + return 'player' + } else { + return 'computer' + } + }, + reset() { + this.playerScore = 0; + this.computerScore = 0; + } +} + +rps.playRound('rock') // returns 'player' if we win... +rps.playerScore // ...and our score would have increased + +// We also have the ability to check the winner and reset the game at any time +rps.getWinningPlayer() // 'player', if we won above round +rps.reset() +``` + +You may be looking at this code and thinking that you personally prefer to split your code between more functions than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object. + +But, there is no rule saying that you can't add those functions to your object as well! A common convention is to prefix methods and properties that you don't intend other people to use with an underscore (`_`). This convention conveys to others that "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". + +Let's see what that looks like! + +```javascript +const rps = { + _options: ['rock', 'paper', 'scissors'], + _getRandomChoice() { + const randomIndex = Math.floor(Math.random() * 3) + return this._options[randomIndex] + }, + _isTie(playerChoice, computerChoice) {return playerChoice === computerChoice}, + _isPlayerWinner(playerChoice, computerChoice) { + if( + (playerChoice === 'rock' && computerChoice === 'scissors') || + (playerChoice === 'paper' && computerChoice === 'rock') || + (playerChoice === 'scissors' && computerChoice === 'paper') + ) { + return true + } else { + return false + } + }, + playerScore: 0, + computerScore: 0, + playRound(playerChoice) { + // if an invalid choice is chosen, throw an error + if(!this._options.includes(playerChoice)) { + throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) + } + + // get the computer's choice + const computerChoice = this._getRandomChoice() + + // determine the winner, apply points if necessary, and return who won + if(this._isTie(playerChoice, computerChoice)) { + return "tie" + } else if(this._isPlayerWinner(playerChoice, computerChoice)) { + this.playerScore++ + return "player" + } else { + this.computerScore++ + return 'computer' + } + }, + getWinningPlayer() { + if(this.playerScore === this.computerScore) { + return 'tie' + } else if (this.playerScore > this.computerScore) { + return 'player' + } else { + return 'computer' + } + }, + reset() { + this.playerScore = 0; + this.computerScore = 0; + } +} +``` + +Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly make them private, you will later learn about other methods of creating objects that *can*. + +Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! + +The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. + +This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. + +Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have a website where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects! + +
+ +#### Objects As Machines + +When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine the object as a little 'machine' you're making out of code that does something useful. + +The properties of the machine could be thought of displays that might show information it's collected or been given to it so far, if it can currently be interacted with, what the machine has counted for a player's score... or about a billion other things, depending on what your object does. + +The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing. A method might give your object new information to store in some way, turn your machine from on 'on' to 'off', allow you to input information to play a game, or switch between the turns of two different players. + +Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. + +
+ +### Assignment + +
+ +1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations. Pay special attention to the pitfalls mentioned in each section. Don't worry too much about understanding the section on Constructor invocation. + +
+ +### Knowledge check + +The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge. + +- [What are two ways you can use objects to organize code?](#objects-as-a-data-structure) +- [What is a 'method'?](#objects-as-a-design-pattern) +- [What is the `this` keyword used for?](#objects-as-a-design-pattern) +- [What methods should exist as part of an object's public interface?](#objects-as-a-design-pattern) + +### Additional resources + +This section contains helpful links to related content. It isn't required, so consider it supplemental. + +- [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by +Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. +- Check out this [video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. From b0e07a5fb0bcab25f8dd88780d4975a224635ca1 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Mon, 1 Jul 2024 11:00:36 -0400 Subject: [PATCH 11/32] remove language indicating object literals are the best way to create objects in most cases --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index ff34f296b0e..01319519cfc 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -2,7 +2,7 @@ In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. -There are multiple ways to define objects but in most cases, it is best to use the **object literal** syntax as follows: +There are multiple ways to define objects, but in many cases **object literal** syntax is used as follows: ```javascript const myObject = { From 3c0e23f09c74fffb907085634d3407724688b46f Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Mon, 1 Jul 2024 11:02:03 -0400 Subject: [PATCH 12/32] clarify what's meant by object literals not having a way to make private methods truly private --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 01319519cfc..e566dc07609 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -286,7 +286,7 @@ const rps = { } ``` -Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly make them private, you will later learn about other methods of creating objects that *can*. +Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly prevent people from using them, you will later learn about other methods of creating objects that *can*. Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! From 3f97244cbf6569bde7daef3fa801386e5f3806d4 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Mon, 1 Jul 2024 11:21:49 -0400 Subject: [PATCH 13/32] remove object organization content to be extracted into a separate lesson --- .../objects_and_object_constructors.md | 312 +----------------- 1 file changed, 3 insertions(+), 309 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 1d0afbc61e8..563ca38ecbb 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -1,318 +1,17 @@ ### Introduction -In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. - -There are multiple ways to define objects but in most cases, it is best to use the **object literal** syntax as follows: - -```javascript -const myObject = { -  property: 'Value!', -  otherProperty: 77, -  "obnoxious property": function() { -    // do stuff! -  } -}; -``` - -There are also 2 ways to get information out of an object: dot notation and bracket notation. - -```javascript -// dot notation -myObject.property; // 'Value!' - -// bracket notation -myObject["obnoxious property"]; // [Function] -``` - -Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you cannot use variables in dot notation: - -```javascript -const variable = 'property'; - -myObject.variable; // this gives us 'undefined' because it's looking for a property named 'variable' in our object - -myObject[variable]; // this is equivalent to myObject['property'] and returns 'Value!' -``` - -If you are feeling rusty on using objects, now might be a good time to go back and review the content in our [object basics lesson](https://www.theodinproject.com/lessons/foundations-object-basics) from our JavaScript Basics course. +Now that you've got a basic understanding of *why* and *how* you might use objects to organize data and functionality into objects, it's important to about some basic strategies for creating creating duplicates of objects, and using existing types of objects as a base for creating new ones. ### Lesson overview This section contains a general overview of topics that you will learn in this lesson. -- Explain how objects can be used to organize data -- Explain how objects can be used to organize functionality -- Explain what the `this` keyword is. +- Explain how the `this` keyword is used in object constructors. - How to write an object constructor and instantiate the object. - Describe what a prototype is and how it can be used. - Explain prototypal inheritance. - Understand the basic do's and don't's of prototypal inheritance. -### Objects as a data structure - -You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: - -```javascript -// example one -const playerOneName = "tim"; -const playerTwoName = "jenn"; -const playerOneMarker = "X"; -const playerTwoMarker = "O"; - -// example two -const playerOne = { - name: "tim", - marker: "X" -}; - -const playerTwo = { - name: "jenn", - marker: "O" -}; -``` - -At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate: - -```javascript -function printName(player) { - console.log(player.name); -} -``` - -This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually console.log it: - -```javascript -console.log(playerOneName); -console.log(playerTwoName); -``` - -Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print? - -```javascript -function gameOver(winningPlayer){ - console.log("Congratulations!"); - console.log(winningPlayer.name + " is the winner!"); -} -``` - -Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum. - -### Objects as a design pattern - -The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). - -The inroductory paragraph for Object Oriented Programming on Wikipedia says this: - -> Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another. - -Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions on an object) that interact with that data. - -Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. - -Let's take an example of some thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: - -```javascript -const lightbulb = { - lightColor: 'fluorescent white', // this lightbulb is white, - lit: false // and is currently 'off' -} -``` - -You may want to have the ability to switch a lightbulb from it's unlit state to it's lit state, or vice-versa. To do that, you might add a *method*. - -The easiest way to get started creating methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from. - -The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`: - -```javascript -const lightbulb = { - lightColor: 'fluorescent white', - lit: false, - - // shorthand syntax for adding methods to objects - switchOn() { - this.lit = true - }, - switchOff() { - this.lit = false - } -} - -lightbulb.switchOn() -lightbulb.lit // true - we switched it on -``` - -These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object. - -Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much. - -Moving past physical objects, we could also try to describe something like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. - -A rock paper scissors game might involve a couple basic things: - -- Players' scores -- The ability to play a round (and playing a round should update a player's score) - -And might also include a couple nice-to-haves - -- The ability to determine the current winning player -- The ability to restart the game - -So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a computer player): - -```javascript -const rps = { - playerScore: 0, - computerScore: 0, - playRound(playerChoice) { - // code to play the round... (and update the scores when a player wins) - } -} -``` - -And if we fleshed it out, our object may come out to look something like this: - -```javascript -const rps = { - playerScore: 0, - computerScore: 0, - playRound(playerChoice) { - const options = ['rock', 'paper', 'scissors'] - - // if an invalid choice is chosen, throw an error - if(!options.includes(playerChoice.toLowerCase())) { - throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) - } - - // get the computer's choice - const computerChoice = options[Math.floor(Math.random() * 3)] - - - // determine the winner, apply points if necessary, and return who won - if(playerChoice.toLowerCase() === computerChoice) { - return "tie" - } else if( - (playerChoice === 'rock' && computerChoice === 'scissors') || - (playerChoice === 'paper' && computerChoice === 'rock') || - (playerChoice === 'scissors' && computerChoice === 'paper') - ) { - this.playerScore++ - return "player" - } else { - this.computerScore++ - return 'computer' - } - }, - getWinningPlayer() { - if(this.playerScore === this.computerScore) { - return 'tie' - } else if (this.playerScore > this.computerScore) { - return 'player' - } else { - return 'computer' - } - }, - reset() { - this.playerScore = 0; - this.computerScore = 0; - } -} - -rps.playRound('rock') // returns 'player' if we win... -rps.playerScore // ...and our score would have increased - -// We also have the ability to check the winner and reset the game at any time -rps.getWinningPlayer() // 'player', if we won above round -rps.reset() -``` - -You may be looking at this code and thinking that you personally prefer to split your code between more functions than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object. - -But, there is no rule saying that you can't add those functions to your object as well! A common convention is to prefix methods and properties that you don't intend other people to use with an underscore (`_`). This convention conveys to others that "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead". - -Let's see what that looks like! - -```javascript -const rps = { - _options: ['rock', 'paper', 'scissors'], - _getRandomChoice() { - const randomIndex = Math.floor(Math.random() * 3) - return this._options[randomIndex] - }, - _isTie(playerChoice, computerChoice) {return playerChoice === computerChoice}, - _isPlayerWinner(playerChoice, computerChoice) { - if( - (playerChoice === 'rock' && computerChoice === 'scissors') || - (playerChoice === 'paper' && computerChoice === 'rock') || - (playerChoice === 'scissors' && computerChoice === 'paper') - ) { - return true - } else { - return false - } - }, - playerScore: 0, - computerScore: 0, - playRound(playerChoice) { - // if an invalid choice is chosen, throw an error - if(!this._options.includes(playerChoice)) { - throw new Error(`Expected 'rock', 'paper', or 'scissors', but got ${playerChoice}`) - } - - // get the computer's choice - const computerChoice = this._getRandomChoice() - - // determine the winner, apply points if necessary, and return who won - if(this._isTie(playerChoice, computerChoice)) { - return "tie" - } else if(this._isPlayerWinner(playerChoice, computerChoice)) { - this.playerScore++ - return "player" - } else { - this.computerScore++ - return 'computer' - } - }, - getWinningPlayer() { - if(this.playerScore === this.computerScore) { - return 'tie' - } else if (this.playerScore > this.computerScore) { - return 'player' - } else { - return 'computer' - } - }, - reset() { - this.playerScore = 0; - this.computerScore = 0; - } -} -``` - -Another name for these might also be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly make them private, you will later learn about other methods of creating objects that *can*. - -Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! - -The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. - -This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. - -Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have a website where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects! - -
- -#### Objects As Machines - -When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine the object as a little 'machine' you're making out of code that does something useful. - -The properties of the machine could be thought of displays that might show information it's collected or been given to it so far, if it can currently be interacted with, what the machine has counted for a player's score... or about a billion other things, depending on what your object does. - -The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing. A method might give your object new information to store in some way, turn your machine from on 'on' to 'off', allow you to input information to play a game, or switch between the turns of two different players. - -Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. - -
- ### Object constructors Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: @@ -574,9 +273,7 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e 1. Read up on the concept of the prototype from the articles below. 1. Read the article [Understanding Prototypes and Inheritance in JavaScript](https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript) from Digital Ocean. This is a good review of prototype inheritance and constructor functions, featuring some examples. 1. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. -1. You might have noticed us using the `this` keyword in object constructors and prototype methods in the examples above. - - 1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations. Pay special attention to the pitfalls mentioned in each section. +1. Take another look at [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/), paying more attention to it's use with constructor functions this time. @@ -584,9 +281,6 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge. -- [Explain two ways you can use objects to organize code.](#objects-as-a-data-structure) -- [What is a 'method'](#objects-as-a-design-pattern) -- [What is the `this` keyword used for?](#objects-as-a-design-pattern) - [Write an object constructor and instantiate the object.](#object-constructors) - [Describe what a prototype is and how it can be used.](#the-prototype) - [Explain prototypal inheritance.](https://javascript.info/prototype-inheritance) From 61e772d963f5e64bf0d364b3ab21c68d9bc279cc Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 2 Jul 2024 18:31:57 -0400 Subject: [PATCH 14/32] change the lesson goal on the `this` keyword to be more general --- .../objects_and_object_constructors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 563ca38ecbb..72c5ff56786 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -6,7 +6,7 @@ Now that you've got a basic understanding of *why* and *how* you might use objec This section contains a general overview of topics that you will learn in this lesson. -- Explain how the `this` keyword is used in object constructors. +- Explain how the `this` behaves in different situations. - How to write an object constructor and instantiate the object. - Describe what a prototype is and how it can be used. - Explain prototypal inheritance. From 3ffb1a21c2d0979b7bae0b3975060470719f3e6b Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 2 Jul 2024 18:32:49 -0400 Subject: [PATCH 15/32] remove references to objects used in 'Organizing Code with Objects' lesson --- .../objects_and_object_constructors.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 72c5ff56786..7fe3d5daadf 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -6,7 +6,7 @@ Now that you've got a basic understanding of *why* and *how* you might use objec This section contains a general overview of topics that you will learn in this lesson. -- Explain how the `this` behaves in different situations. +- Explain how the `this` keyword behaves in different situations. - How to write an object constructor and instantiate the object. - Describe what a prototype is and how it can be used. - Explain prototypal inheritance. @@ -14,7 +14,7 @@ This section contains a general overview of topics that you will learn in this l ### Object constructors -Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate like our player object, inventory items, or even the entire RPS game, a better way to create them is using an object constructor, which is a function that looks like this: +Manually typing out the contents of our objects with Object Literals is not always feasible. When you have a specific type of object that you need to duplicate, a better way to create them is using an object constructor, which is a function that looks like this: ```javascript function Player(name, marker) { From 4cad12f1bea3365b7c6c193044a7f5b6d5f3a19f Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 2 Jul 2024 21:57:20 -0400 Subject: [PATCH 16/32] change the assignment to use the easier devsage video --- .../organizing_code_with_objects.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index e566dc07609..6d5fd8cea0c 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -314,7 +314,7 @@ Again, objects can be used to represent almost anything you can think of, the li
-1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations. Pay special attention to the pitfalls mentioned in each section. Don't worry too much about understanding the section on Constructor invocation. +1. Check out this [video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson.
@@ -333,4 +333,4 @@ This section contains helpful links to related content. It isn't required, so co - [The Principles of Object-Oriented JavaScript](https://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404) book by Nicholas C. Zakas is really great to understand OOP in JavaScript, which explains concepts in-depth, which explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics, it's not free but it's very valuable. -- Check out this [video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. +- [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations. From 19da94ca40ee78493e19b9b722d551fde386e578 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 2 Jul 2024 22:09:04 -0400 Subject: [PATCH 17/32] edit assignment wording so it doesn't feel as if it's the first time the learner is hearing about the `this` keyword --- .../objects_and_object_constructors.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 7fe3d5daadf..2a8b1eedf47 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -273,7 +273,8 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e 1. Read up on the concept of the prototype from the articles below. 1. Read the article [Understanding Prototypes and Inheritance in JavaScript](https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript) from Digital Ocean. This is a good review of prototype inheritance and constructor functions, featuring some examples. 1. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. -1. Take another look at [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/), paying more attention to it's use with constructor functions this time. +1. You might have noticed us using the this keyword in object constructors and prototype methods in the examples above. + 1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how this changes in various situations, including examples with constructor functions and the prototype. @@ -294,4 +295,3 @@ This section contains helpful links to related content. It isn't required, so co - This [`Object.create` method video by techsith](https://www.youtube.com/watch?v=MACDGu96wrA) provides another point of view on how to use `Object.create` to extend objects by setting the prototype. - The first answer on this StackOverflow question regarding [defining methods via the prototype vs in the constructor](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) helps explain when you might want to use one over the other. - [Interactive Scrim on objects and object constructors.](https://scrimba.com/scrim/co2624f87981575448091d5a2) -- Check out this video explanation on the [`this` keyword from DevSage](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. From 9535e552e51b89bf2ec3564cf09b45f1eea8be69 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Wed, 10 Jul 2024 18:44:30 -0400 Subject: [PATCH 18/32] Fix new introduction to lesson --- .../objects_and_object_constructors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 31841af9651..47ea9b35ec2 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -1,6 +1,6 @@ ### Introduction -Now that you've got a basic understanding of *why* and *how* you might use objects to organize data and functionality into objects, it's important to about some basic strategies for creating creating duplicates of objects, and using existing types of objects as a base for creating new ones. +Now that you've got a basic understanding of *why* and *how* you might use objects to organize data and functionality, it's important to learn some basic strategies for creating duplicates (often called *instances*) of objects, and using existing types of objects as a base for creating new ones through *inheritance*. ### Lesson overview From 73def3be3a4abda695f5fd96aacc3efe313c4508 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 23 Jul 2024 06:54:33 -0400 Subject: [PATCH 19/32] make small editorial changes --- .../organizing_code_with_objects.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 6d5fd8cea0c..2b9462cc0ab 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -106,7 +106,7 @@ Essentially, what this means is that code can be organized into objects that con Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. -Let's take an example of some thing- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: +Let's take an example of some *thing*- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: ```javascript const lightbulb = { @@ -143,7 +143,7 @@ These methods use the `this` keyword to refer to the object they get called from Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much. -Moving past physical objects, we could also try to describe something like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. +Moving past physical items, we could also try to describe something a little bit more abstract like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example. A rock paper scissors game might involve a couple basic things: @@ -290,7 +290,7 @@ Another name for these might also be **private properties**/**private methods**, Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! -The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. +The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**, or **public properties**/**public methods**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. From 86f89927d7c64779aaf1efe7017ba990a8737e1e Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 23 Jul 2024 06:55:55 -0400 Subject: [PATCH 20/32] add lesson exercises --- .../organizing_code_with_objects.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 2b9462cc0ab..1f730e77afb 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -316,6 +316,32 @@ Again, objects can be used to represent almost anything you can think of, the li 1. Check out this [video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson. +1. Try modelling the behavior of a piggy bank as an object: + 1. You should be able to interact with the object via a method that allows you to deposit coins. + - For now, use a string to represent the name of a coin. Ex. `piggyBank.deposit('penny')` + - You should keep the coin around by storing it in some kind of list. + 1. The object should also have a property or method that tells you how much money you have saved as a number. + - For simplicity, using only the smallest subunit of a given currency is acceptable. + - Ex: If there are 5 US quarters in the piggy bank, then the number `125` for '125 cents' is acceptable. + 1. You should be able to read the list of all coins that are currently in the piggy bank. + 1. Add a method to the piggy bank object to remove a specific type of coin from the piggy bank if it's available. + - Ensure you can still get the correct savings after removing coins! + 1. Lastly, create a way to remove all the money from the jar and start fresh. + +1. Try to model something else as an object! Try to keep it simple. When you're done, consider showing off what you've created on [The Odin Project's Discord Channel](https://discord.com/invite/fbFCkYabZB), and tell us how you're feeling about the idea of organizing code into objects. + +#### Extra credit + +1. You may have exposed the list that the piggy bank uses to track coins as a public property. Depending on how you implemented the piggy bank, modifying this list without using something like a `deposit` or `withdraw` method on the object could throw some of it's properties out of wack, like the one that tells you the amount of savings you've accrued. Additionally, adding an unexpected value to this list by modifying it directly could cause errors within your piggy bank methods. Let's try to ensure that doesn't happen! + - Indicate that the list of coins the piggy bank uses is a **private property** of the object. + - Create a **public method** that gives the user a *copy* of the list that they can manipulate to their hearts content without breaking the piggy bank object. + +1. Try creating a couple 'coin' objects to deposit into the piggy bank instead of using a string. + - A coin object might contain properties like the name of the coin, and it's value (preferably in the same unit the piggy bank measures it's savings). + - Make sure that your piggy bank object is still able to keep track of savings and remove coins correctly after this change! + - After making this change, consider how you are calculating savings for the piggy bank compared to before. Do you prefer working with the objects or the strings more? + - Consider how the piggy bank might check for a correct string vs checking for an object with the correct properties when depositing. Which seems easier? Does one seem more flexible than the other? + ### Knowledge check From 2e2246f5a0eac4e773347144b24904733143f20c Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 23 Jul 2024 06:57:00 -0400 Subject: [PATCH 21/32] Make the 'objects as machines' subsection clearer --- .../organizing_code_with_objects.md | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 1f730e77afb..aa3a957d175 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -296,19 +296,29 @@ This idea of grouping related functionality within an object is *extremely power Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have a website where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects! -
+### Objects As Machines -#### Objects As Machines - -When you want to organize some data and functionality together in this way, but you're having trouble figuring out what kinds of properties and methods an object might contain when it's not an actual, physical item, another way you might conceptualize this idea might be to imagine the object as a little 'machine' you're making out of code that does something useful. +Sometimes, you may want to create objects that embody complex concepts rather actual, physical items- similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be: -The properties of the machine could be thought of displays that might show information it's collected or been given to it so far, if it can currently be interacted with, what the machine has counted for a player's score... or about a billion other things, depending on what your object does. +- An object that manages other objects, such as an "inventory" object that contains a list of items, and actions that can be done with those items. +- An object that can listen for events that happen, and respond appropriately (think of `.addEventListener` on DOM elements) +- A "Debt" object that keeps track of a debt owed, how much has been paid, and how much of the debt is remaining. -The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing. A method might give your object new information to store in some way, turn your machine from on 'on' to 'off', allow you to input information to play a game, or switch between the turns of two different players. +You may have trouble figuring out what kinds of properties and methods one of these objects might contain at first. One way you might conceptualize these objects might be to imagine them as little 'machines' you're making out of code. -Again, objects can be used to represent almost anything you can think of, the limit is your imagination! It's impossible for us to give a comprehensive list of examples. +The properties of the machine could be thought of displays that might show information such as: -
+- A list of the items you've collected, the total amount of items you can carry, and how much you're currently carrying +- A list of functions that are listening for an event +- The person who owes a particular debt, and the original amount owed. + +The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing, such as: + +- Remove an item you own from a list, add a new item, upgrade an item, craft a new item +- Fire all the functions that are listening to a 'click' event, or add a new function to listen to the 'click' event +- Pay an amount of money towards a debt, and determine how much more money is owed on a debt + +Again, objects can be used to represent almost anything you can think of, the limit is your imagination! ### Assignment From 16cbddf0cb2bb42d09e85127abe42f40504f6a0e Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Tue, 23 Jul 2024 12:11:41 -0400 Subject: [PATCH 22/32] Split long paragraph into two --- .../organizing_code_with_objects.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index aa3a957d175..53582f26148 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -342,7 +342,9 @@ Again, objects can be used to represent almost anything you can think of, the li #### Extra credit -1. You may have exposed the list that the piggy bank uses to track coins as a public property. Depending on how you implemented the piggy bank, modifying this list without using something like a `deposit` or `withdraw` method on the object could throw some of it's properties out of wack, like the one that tells you the amount of savings you've accrued. Additionally, adding an unexpected value to this list by modifying it directly could cause errors within your piggy bank methods. Let's try to ensure that doesn't happen! +1. You may have exposed the list that the piggy bank uses to track coins as a public property. Depending on how you implemented the piggy bank, modifying this list without using something like a `deposit` or `withdraw` method on the object could throw some of it's properties out of wack, like the one that tells you the amount of savings you've accrued. + + Additionally, adding an unexpected value to this list by modifying it directly could cause errors within your piggy bank methods. Let's try to ensure that doesn't happen! - Indicate that the list of coins the piggy bank uses is a **private property** of the object. - Create a **public method** that gives the user a *copy* of the list that they can manipulate to their hearts content without breaking the piggy bank object. From 28c8b5a9d0781b0fc71a654f40c37e61e55abf95 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Wed, 21 Aug 2024 00:11:55 -0400 Subject: [PATCH 23/32] fix unescaped underscores --- .../objects_and_object_constructors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 2f808ce82a8..b7a22cc13bf 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -275,7 +275,7 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e 1. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. 1. You might have noticed us using the this keyword in object constructors and prototype methods in the examples above. 1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how this changes in various situations, including examples with constructor functions and the prototype. -1. Read the article [[[Prototype]] vs __proto__ vs .prototype in Javascript](https://medium.com/@eamonocallaghan/prototype-vs-proto-vs-prototype-in-javascript-6758cadcbae8) +1. Read the article [[[Prototype]] vs \_\_proto\_\_ vs .prototype in JavaScript](https://medium.com/@eamonocallaghan/prototype-vs-proto-vs-prototype-in-javascript-6758cadcbae8) From e7c08dd5024298cf310bd63646adb80534fe1879 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 14:47:16 -0400 Subject: [PATCH 24/32] Rearrange introductory content with editorial changes. --- .../organizing_code_with_objects.md | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 53582f26148..a0df3829c69 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -1,6 +1,17 @@ ### Introduction -In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. +In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. In this lesson, we'll start with a little refresher, then explore using objects in more detail. + +### Lesson overview + +This section contains a general overview of topics that you will learn in this lesson. + +- Using objects to organize data. +- Using objects to organize functionality. +- Object methods and the `this` keyword. +- Public and private interfaces. + +### Refresher There are multiple ways to define objects, but in many cases **object literal** syntax is used as follows: @@ -27,24 +38,15 @@ myObject["obnoxious property"]; // [Function] Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you cannot use variables in dot notation: ```javascript -const variable = 'property'; +const variable = "property"; -myObject.variable; // this gives us 'undefined' because it's looking for a property named 'variable' in our object +// 'undefined' because it's looking for a property named 'variable' in our object +myObject.variable; -myObject[variable]; // this is equivalent to myObject['property'] and returns 'Value!' +// this is equivalent to myObject['property'] and returns 'Value!' +myObject[variable]; ``` -If you are feeling rusty on using objects, now might be a good time to go back and review the content in our [object basics lesson](https://www.theodinproject.com/lessons/foundations-object-basics) from our JavaScript Basics course. - -### Lesson overview - -This section contains a general overview of topics that you will learn in this lesson. - -- Using objects to organize data. -- Using objects to organize functionality. -- Object methods and the `this` keyword -- Public and private interfaces - ### Objects as a data structure You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: From 965e4792acb0cdcedeb14d6804f4702e1ffa99d3 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 14:54:42 -0400 Subject: [PATCH 25/32] prefix dashes with spaces --- .../organizing_code_with_objects.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index a0df3829c69..7c676c5c2b7 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -49,7 +49,7 @@ myObject[variable]; ### Objects as a data structure -You've already been introduced to the basic use of a JavaScript object- storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: +You've already been introduced to the basic use of a JavaScript object - storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game: ```javascript // example one @@ -98,7 +98,7 @@ Or, what if we aren't making a 2 player game, but something more complicated suc ### Objects as a design pattern -The grouping power of objects isn't just useful for organizing data- it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). +The grouping power of objects isn't just useful for organizing data - it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). The inroductory paragraph for Object Oriented Programming on Wikipedia says this: @@ -108,7 +108,7 @@ Essentially, what this means is that code can be organized into objects that con Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. -Let's take an example of some *thing*- we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: +Let's take an example of some *thing* - we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an 'on' state, or an 'off' state. These might be expressed as properties of a lightbulb object: ```javascript const lightbulb = { @@ -292,7 +292,7 @@ Another name for these might also be **private properties**/**private methods**, Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters! -The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**, or **public properties**/**public methods**. Having a good, well thought out interface on your objects is important- not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. +The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**, or **public properties**/**public methods**. Having a good, well thought out interface on your objects is important - not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future. This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code. @@ -300,7 +300,7 @@ Furthermore, with the various object creation methods you'll learn throughout th ### Objects As Machines -Sometimes, you may want to create objects that embody complex concepts rather actual, physical items- similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be: +Sometimes, you may want to create objects that embody complex concepts rather actual, physical items - similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be: - An object that manages other objects, such as an "inventory" object that contains a list of items, and actions that can be done with those items. - An object that can listen for events that happen, and respond appropriately (think of `.addEventListener` on DOM elements) From 1da76cc249c831380011b642a562d2e933d76614 Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:02:07 -0400 Subject: [PATCH 26/32] fix spelling error Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 7c676c5c2b7..87be568b84f 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -100,7 +100,7 @@ Or, what if we aren't making a 2 player game, but something more complicated suc The grouping power of objects isn't just useful for organizing data - it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP). -The inroductory paragraph for Object Oriented Programming on Wikipedia says this: +The introductory paragraph for Object Oriented Programming on Wikipedia says this: > Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another. From cf99f6ad85b6a667b43ee06b9a47022326eb1eb5 Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:03:53 -0400 Subject: [PATCH 27/32] small editorial change Change 'functions on an object' to 'functions in an object' Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 87be568b84f..b8e3a09fc69 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -104,7 +104,7 @@ The introductory paragraph for Object Oriented Programming on Wikipedia says thi > Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another. -Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions on an object) that interact with that data. +Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions in an object) that interact with that data. Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods. From c7d0270d20f6b8d66940a04daf8beddcea7a64ad Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:07:05 -0400 Subject: [PATCH 28/32] Small editorial change replace it's with its Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index b8e3a09fc69..ace734a4c54 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -157,7 +157,7 @@ And might also include a couple nice-to-haves - The ability to determine the current winning player - The ability to restart the game -So, at it's most basic, an object that represents the game might look something like this (assuming we're playing against a computer player): +So, at its most basic, an object that represents the game might look something like this (assuming we're playing against a computer player): ```javascript const rps = { From d46a1f02d2ef77fefd5c48fe984dab224b18587f Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:10:35 -0400 Subject: [PATCH 29/32] Fix heading case to conform to style guide Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index ace734a4c54..ed40af89e3e 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -298,7 +298,7 @@ This idea of grouping related functionality within an object is *extremely power Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have a website where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects! -### Objects As Machines +### Objects as machines Sometimes, you may want to create objects that embody complex concepts rather actual, physical items - similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be: From 65a5b447fe8d63e60ad4cc80b931b76f6367dc13 Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:17:28 -0400 Subject: [PATCH 30/32] Supply accessable link Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index ed40af89e3e..426ce74b4cd 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -326,7 +326,7 @@ Again, objects can be used to represent almost anything you can think of, the li
-1. Check out this [video explanation](https://www.youtube.com/watch?v=cwChC4BQF0Q) on the `this` keyword from DevSage that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson. +1. Check out [DevSage's video explanation of the `this` keyword](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson. 1. Try modelling the behavior of a piggy bank as an object: 1. You should be able to interact with the object via a method that allows you to deposit coins. From af9ce688cddbfe5b2ae1856f093097e13dbb00ce Mon Sep 17 00:00:00 2001 From: takinabradley <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:42:16 -0400 Subject: [PATCH 31/32] Add period at end of assignment Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --- .../objects_and_object_constructors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md index 0a8b62529c8..6bc1171cb6a 100644 --- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md +++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md @@ -275,7 +275,7 @@ If we had used `Object.setPrototypeOf()` in this example, then we could safely e 1. To go a bit deeper into both the chain and inheritance, spend some time with [JavaScript.Info's article on Prototypal Inheritance](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: This article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. 1. You might have noticed us using the this keyword in object constructors and prototype methods in the examples above. 1. [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how this changes in various situations, including examples with constructor functions and the prototype. -1. Read the article [[[Prototype]] vs \_\_proto\_\_ vs .prototype in JavaScript](https://medium.com/@eamonocallaghan/prototype-vs-proto-vs-prototype-in-javascript-6758cadcbae8) +1. Read the article [[[Prototype]] vs \_\_proto\_\_ vs .prototype in JavaScript](https://medium.com/@eamonocallaghan/prototype-vs-proto-vs-prototype-in-javascript-6758cadcbae8).
From 218d97a606c7bc90b26001790b9cbd7d1ec78492 Mon Sep 17 00:00:00 2001 From: Bradley Finney <77649883+takinabradley@users.noreply.github.com> Date: Sat, 12 Oct 2024 17:53:33 -0400 Subject: [PATCH 32/32] Describe how knowing what methods/properties should be on an objects public interface comes with experience --- .../organizing_code_with_objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md index 426ce74b4cd..3cc8108527f 100644 --- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md +++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md @@ -306,7 +306,7 @@ Sometimes, you may want to create objects that embody complex concepts rather ac - An object that can listen for events that happen, and respond appropriately (think of `.addEventListener` on DOM elements) - A "Debt" object that keeps track of a debt owed, how much has been paid, and how much of the debt is remaining. -You may have trouble figuring out what kinds of properties and methods one of these objects might contain at first. One way you might conceptualize these objects might be to imagine them as little 'machines' you're making out of code. +You may have trouble figuring out what public interface of these objects might contain at first. These sorts of things come with experience, and concepts taught in later lessons can help as well. One way you might conceptualize these objects, though, might be to imagine them as little 'machines' you're making out of code. The properties of the machine could be thought of displays that might show information such as: