@jgCarroll/

makingAnObject

JavaScript

A common interview question

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// object literal syntax. Most common way to make an object.

const myBoat = {
  length: 24,
  maxSpeed: 45,
  passengers: 14,
  getLength: function() {
    return this.length
  }
}

// ================================
// new keyword & Object constructor

const student = new Object()

student.grade = 12
student.gradePointAverage = 3.7
student.classes = ['English', 'Algebra', 'Chemistry']

student.getClasses = function() {
  return this.classes
}

// ==================================
// constructor function. Best for making many objects of the same kind

function Car(color, brand, year) {
  this.color = color
  this.brand = brand
  this.year = year
}

Car.prototype.getColor = function() {
  return this.color
}

const carlysCar = new Car('blue', 'Ferarri', 2015)
const jimsCar = new Car('red', 'Tesla', 2014)

console.log(carlysCar.getColor())
console.log(jimsCar)
Native Browser JavaScript