JavaScript Objects

Dr. Greg Bernstein

Updated August 29th, 2019

Objects

Readings/References

Ways of Creating Objects

  • Via an object literal: let myObj = {};

  • Via the Object constructor: let myObj = new Object();

  • Via constructor functions, Object.create(), and Object.assign(). We’ll discuss these a bit later.

Setting and Getting Object Properties

  • Via “dot” notation
var myObj = {};
// create the property color and assign to it
myObj.color = "red";
console.log(myObj.color);
console.log(myObj.temperature); // Returns undefined

Setting and Getting Object Properties

  • Via “python dictionary” like notation
var myObj = {};
// create the property color and assign to it
myObj["color"] = "blue";
console.log(myObj["color"]);
console.log(myObj["temperature"]); // Returns undefined

Example: Look up table

Maps words to numbers

var myArray = ["zero", "one", "two", "three"];
var myLook = {};
for (var i = 0; i < myArray.length; i++) {
    myLook[myArray[i]] = i;
}
console.log(myLook);

Copying and Combining Objects

By Reference or By Value

Primitives are copied by value, changing b below does not change a

var a = 3;
var b = a;
var b = 17;
console.log(`a = ${a}, b = ${b}`);

By Reference or By Value

myObj = {wind: 22, tide: 4.1};
myObj2 = myObj;
myObj2.tide = 2.7;
console.log(myObj, myObj2);

How to Copy Objects

  • JavaScript doesn’t have an object copy function
  • It has something much better
  • It is Object.assign

Copying JavaScript Objects

myObj = {wind: 22, tide: 4.1};
myObj2 = Object.assign({}, myObj);
myObj2.tide = 2.7;
console.log(myObj, myObj2);

Object.assign

  • Syntax: Object.assign(target, ...sources)

  • Object.assign() is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Combining JavaScript Objects

myKiteStuff = {kites: ["11m", "13m"], kiteBoard: "TwinTip 151"};
myWindsurfStuff = {sails: ["7.7m", "6.6m", "5.9m", "5.5m"], windsurfBoard: "Foiling Board"};
myCar = Object.assign({driver: "Dr. B"}, myKiteStuff, myWindsurfStuff);
console.log(myCar);

Updating/Overriding

Run this in your browser console!

var course = {code: "CS351", name: "website dev", instructor: "Dr. B"};
var session = {id: "78sf234", enrolled: 32, auditing: 1};
Object.assign(course, session);
console.log(course);
console.log(session);
var update = {id: "78sf234", enrolled: 300, auditing: 10};
Object.assign(course, update);
console.log(course);

Removing Fields (delete)

Run this in your browser console!

var course = {code: "CS351", name: "website dev", instructor: "Dr. B"};
var session = {id: "78sf234", enrolled: 32, auditing: 1};
Object.assign(course, session);
console.log(course);
delete course.auditing;
console.log(course);

Object Methods

Object Methods I

Three ways to specify object methods. With “dot” notation:

var course = {name: "Web Dev", instructor: "Dr. B"};
course.summary = function() {
    return `${this.name} with ${this.instructor}!`;
}

course.summary();

Object Methods II

As an object property:

var windsAndTide = {
    location: "The Bay",
    disclaimer: "Not for Navigation",
    wind: function() {
        let speed = 30*Math.random();
        return `${this.location} wind: ${speed.toFixed(2)} miles per hour`;
    },
    tide: function() {
        let height = 7*Math.random();
        return `${height.toFixed(2)} feet`;
    }
}
windsAndTide.wind();
windsAndTide.tide();

Object Methods III

As an internal function:

var windsAndTide = {
    location: "The Bay",
    disclaimer: "Not for Navigation",
    wind() { // No : or function needed!
        let speed = 30*Math.random();
        return `${this.location} wind: ${speed.toFixed(2)} miles per hour`;
    },

    tide() {
        let height = 7*Math.random();
        return `${height.toFixed(2)} feet`;
    }
}
windsAndTide.wind();
windsAndTide.tide();

Object Constructor Functions

Reference

Via an object Constructor Function 1

function Board() {
    this.year = 2010;
    this.make = "Mikes Lab";
    this.weight = "10lbs";
    this.style = "Formula";
    this.about = function() {
        return `${this.year} ${this.make} ${this.style} board`;
    } // Can't just write the method name :-<
}

Object Constructor Function

Must use new with constructor functions. Hence convention that constructor functions start with a capital letter.

  • Right var myBoard = new Board();

  • Wrong var myBoard = Board();

Try it!

What’s going on?

  • Using new with a function constructor creates an new object (we’ll see how this can be controlled) and sets this to that object.

  • The rest of the statements using this just “populate” the object.

  • When the constructor finishes the object associate with this is returned.

Forgot new?

  • Not using new leaves this set to the default (in a browser the Window object).

  • Did you just set properties on Window?

  • Take a look window.make?

instanceof

From MDN: The instanceof operator tests whether an object in its prototype chain has the prototype property of a constructor.

myBoard instanceof Board
myBoard instanceof Date
myBoard instanceof Object