OOJS: Object Creation

How To Make An Object

Making an object from scratch

let circle = {};
circle.radius = 2;
circle.circumference = function() {
    return Math.PI * 2 * this.radius;
};
circle.area = function() {
    return Math.PI * this.radius * this.radius;
};
circle.radius; // 2
circle.area;   // function () { ... }
circle.area(); // 12.566370614359172

Making an object from scratch, literally

The following code is equivalent to the previous slide, but easier to read:

let circle = {
    radius: 2,
    circumference: function() {
        return Math.PI * 2 * this.radius;
    },
    area: function() {
        return Math.PI * this.radius * this.radius;
    }
};
circle.radius; // 2
circle.area;   // function () { ... }
circle.area(); // 12.566370614359172

Methods are Functions, Not Values

Beware of the difference between value properties and method properties!

the class keyword

In 2015, JavaScript introduced the class keyword which is syntactic sugar on top of JavaScript's existing prototype system.

This new class syntax is much easier to understand than the previous system.

class Circle {
  circumference() {
    return Math.PI * this.radius * 2;
  }
  area() {
    return Math.PI * this.radius * this.radius;
  }
}

Use it like this:

let circle = new Circle();  // create a new Circle instance
circle.radius = 2;          // set its radius to 2
circle.area();              // call the area method, which
                            // returns 12.566370614359172 

MDN: classes

Stay classy, JavaScript

This is the first time we've seen classes in JavaScript

Classes are for making lots of objects with the same methods, but different data

A class defines a type of object.

An instance is an individual object of that type.

For example, there are many houses, but my house is yellow.

The Cookie Analogy:

Constructors and "new"

What new does, in detail:

Constructors are for Initialization

the principle of Complete Construction says that after the constructor executes, the object is in a valid state

in practice, this means "pass all initial values into the constructor"

A Better Circle:

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  circumference() {
    return Math.PI * this.radius * 2;
  }
  area() {
    return Math.PI * this.radius * this.radius;
  }
}

Use it like this:

let circle = new Circle(2);  // create a new Circle instance
                             // with radius 2
circle.area();              // call the area method, which
                            // returns 12.566370614359172 

Q: Why is this better?

A: because it preserves encapsulation -- the idea that an object should be responsible for setting its own properties

Constructors are for Validation

constructors are a great place to validate your values

class Circle {
    constructor(radius) {
        if (radius <= 0) {
            throw('radius must be a positive number')
        }
        this.radius = radius;
    }

Factory Town

Sometimes one constructor just isn't enough.

When the constructor accepts different parameters from the ones that you have on hand, you could define a factory function like this:

function circleFromDiameter(diameter) {
    return new Circle(diameter / 2);
}

The above is called a "factory function" since it constructs objects for you, based on your specifications.

Factory Methods

For convenience and code organization, factory functions are often attached to the class -- not the instance -- of the objects they create.

Factory Function Factory Method
let c = circleFromDiameter(2) let c = Circle.fromDiameter(2)

The factory method works exactly the same way as the factory function, but

To make a factory method in JavaScript, use the static keyword:

class Circle {
  static fromDiameter(diameter) {
    return new Circle(diameter / 2);
  }

  constructor(radius) {
    if (radius <= 0) {
        throw('radius must be a positive number')
    }
    this.radius = radius;
  }

  circumference() {
    return Math.PI * this.radius * 2;
  }

  area() {
    return Math.PI * this.radius * this.radius;
  }
}

and call it like this:

let circle = Circle.fromDiameter(4)

Note that (lowercase "c") circle.fromDiameter() does not work. Static methods are attached to classes, not instances.

Classes and Constructors (old way)

Prior to 2015 -- and still today under the hood -- a class is really a pointer to a constructor function.

Defining a class required writing code like this:

var Circle = function(radius) {
    this.radius = radius;
    this.diameter = function() {
      return this.radius * 2;
    }
    this.circumference = function() {
        return Math.PI * 2 * this.radius;
    }
    this.area = function() {
        return Math.PI * this.radius * this.radius;
    }
};

You shouldn't need to write code like this anymore, but you should be able to recognize it if you see it.

 Previous Next 

Outline

[menu]

/