DEV Community

- -
- -

Posted on

TOP - Objects and Object Constructors

TOP

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!
  }
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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

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

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'

Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

The prototype

Top comments (1)

Collapse
 
slobodan4nista profile image
Slobi

The righter way to JS. Thanks for sharing!