Objects and Object Constructors (TOP)

·

3 min read

theOdinProject

Introduction

There are multiple ways to define objects but in most cases, it is best to use the object literal syntax as follows:

const myObject = {
  property: 'Value!',
  otherProperty: 77,
  "obnoxious property": function() {
    // do stuff!
  }
};

There are also 2 ways to get information out of an object:

  1. dot notation myObject.property; // 'Value!'

  2. square bracket notation myObject["obnoxious property"]; // [Function]

Which method you use will depend on context. Dot notation is cleaner and is usually preferred

you cannot use variables in dot notation:

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

Lesson overview

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

  • 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.

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:

function Player(name, marker) {
  this.name = name;
  this.marker = marker;
}

and which you use by calling the function with the keyword new.

const player = new Player('steve', 'X');
console.log(player.name); // 'steve'

Just like with objects created using the Object Literal method, you can add functions to the object:

function Player(name, marker) {
  this.name = name;
  this.marker = marker;
  this.sayName = function() {
    console.log(name)
  };
}

const player1 = new Player('steve', 'X');
const player2 = new Player('also steve', 'O');
player1.sayName(); // logs 'steve'
player2.sayName(); // logs 'also steve'

Exercise

  • Write a constructor for making “Book” objects

  • Your book objects should have the book's title, author and number of pages, and whether or not you have read the book

  • 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"

The prototype

All objects in JavaScript have a prototype. Stated simply, the prototype is another object that the original object inherits from.

the original object has access to all of its prototype’s methods and properties.

1. All objects in JavaScript have a prototype

2. Stated simply, the prototype is another object…

  1. …that the original object inherits from, and has access to all of its prototype’s methods and properties