Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Objects and Object Constructors: Add examples of grouping functionality with objects #27381

Open
wants to merge 44 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 34 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
608cd00
Lint 'objects_and_object_constructors.md'
takinabradley Feb 16, 2024
e3e36f9
Add examples of how objects are useful both to organize data and to g…
takinabradley Feb 16, 2024
77d0a71
Fix spelling errors
takinabradley Feb 16, 2024
cfce9a2
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Feb 18, 2024
d6366b5
Add additional examples of objects as a design pattern
takinabradley Feb 18, 2024
098d451
fix never-ending note
takinabradley Feb 18, 2024
9b9e4a1
small editorial changes
takinabradley Feb 18, 2024
4e581ea
update language to fit the topic of objects representing more abstrac…
takinabradley Feb 18, 2024
53bdcaa
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Feb 26, 2024
f89e4c6
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Feb 28, 2024
afef9e9
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Mar 2, 2024
827614d
fix code tags, apostrophes, and spelling errors
takinabradley Mar 9, 2024
6c96f0c
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Mar 9, 2024
9cb829e
remove unnecessary switchOn/switchOff logic
takinabradley Mar 9, 2024
a202e02
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Jun 23, 2024
86c5ca7
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Jul 1, 2024
b78f821
add a new lesson on organizing code with objects
takinabradley Jul 1, 2024
b0e07a5
remove language indicating object literals are the best way to create…
takinabradley Jul 1, 2024
3c0e23f
clarify what's meant by object literals not having a way to make priv…
takinabradley Jul 1, 2024
3f97244
remove object organization content to be extracted into a separate le…
takinabradley Jul 1, 2024
61e772d
change the lesson goal on the `this` keyword to be more general
takinabradley Jul 2, 2024
3ffb1a2
remove references to objects used in 'Organizing Code with Objects' l…
takinabradley Jul 2, 2024
4cad12f
change the assignment to use the easier devsage video
takinabradley Jul 3, 2024
19da94c
edit assignment wording so it doesn't feel as if it's the first time …
takinabradley Jul 3, 2024
d1ba7bf
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Jul 10, 2024
9535e55
Fix new introduction to lesson
takinabradley Jul 10, 2024
73def3b
make small editorial changes
takinabradley Jul 23, 2024
86f8992
add lesson exercises
takinabradley Jul 23, 2024
2e2246f
Make the 'objects as machines' subsection clearer
takinabradley Jul 23, 2024
16cbddf
Split long paragraph into two
takinabradley Jul 23, 2024
e5be024
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Jul 29, 2024
61e1d38
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Aug 21, 2024
28c8b5a
fix unescaped underscores
takinabradley Aug 21, 2024
88275cb
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Sep 21, 2024
a93de3c
Merge branch 'main' of github.com:TheOdinProject/curriculum into why_…
takinabradley Oct 12, 2024
e7c08dd
Rearrange introductory content with editorial changes.
takinabradley Oct 12, 2024
965e479
prefix dashes with spaces
takinabradley Oct 12, 2024
1da76cc
fix spelling error
takinabradley Oct 12, 2024
cf99f6a
small editorial change
takinabradley Oct 12, 2024
c7d0270
Small editorial change
takinabradley Oct 12, 2024
d46a1f0
Fix heading case to conform to style guide
takinabradley Oct 12, 2024
65a5b44
Supply accessable link
takinabradley Oct 12, 2024
af9ce68
Add period at end of assignment
takinabradley Oct 12, 2024
218d97a
Describe how knowing what methods/properties should be on an objects …
takinabradley Oct 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,103 +1,20 @@
### 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, 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

This section contains a general overview of topics that you will learn in this lesson.

- 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.
- Understand the basic do's and don't's of prototypal inheritance.
- Explain what the `this` keyword is.

### Objects as a design pattern

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:

```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! 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 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...

### 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 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) {
Expand Down Expand Up @@ -356,10 +273,9 @@ 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. Read the article [[[Prototype]] vs __proto__ vs .prototype in Javascript](https://medium.com/@eamonocallaghan/prototype-vs-proto-vs-prototype-in-javascript-6758cadcbae8)
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)
takinabradley marked this conversation as resolved.
Show resolved Hide resolved

</div>

Expand All @@ -380,4 +296,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.
Loading