Objects & JSON

Objectives

  • Identify likely objects, attributes, and methods in real-world scenarios
  • Write a constructor for a JavaScript object
  • Write a prototype method for a JavaScript object
  • Implement and interface with JSON data

Review

  • Understand fundamental data types
  • Execute functions and understand scope
  • Use control flow to manage the flow of information in our programs

Objects

myObject = {
  name: 'Jessica',
  age: 31,
  favAnimal: 'cat',
  isAwesome: true,
}

JS uses Objects in 2 ways

  • As simple structured data store, similar to arrays, the main difference being that instead of accessing our values by index, we access them by a key.
  • As a fundamental programming paradigm that helps us structure and categorize our code.

Creating Objects

var myHouse = {};
var myCar = new Object();
 

var myMotorcycle = {
    wheels: 2,
    color: "blue",
    maxSpeed: 300,
    owners: ["Sofia", "Rose"]
  }

Setting object properties

  myHouse.windows = 6;
  myHouse.address = "Jess Manor, Gotham City";

  myCar["num-of-wheels"] = 4;
  myCar["doors"] = 2;

Access object properties

 myHouse.windows; //returns 6
 myHouse.address; // returns "Jess Manor";

 myCar["num-of-wheels"]; // returns 4;

 var numDoors = "doors";
 myCar[numDoors]; // returns 2;

Iterate through objects

  for (var i in myHouse) {
    if (myHouse.hasOwnProperty(i)) { 
    // The "hasOwnProperty method returns true 
    // if an object property has a certain key"
        console.log(i + " = " + myHouse[i] + "\n");
    }
  }

Copying objects

var myHouse = {
 doors: 2
}

var yourHouse = myHouse;
  yourHouse.doors; // returns 2
  myHouse.doors; // returns 2

  yourHouse.doors = 4;
  myHouse.doors; // returns 4

Real World Objects

E-Commerce store

Practice!

  • Reporting software analyzes the snow removal performance of each snow plow driver in the city.

  • A simulation predicts the behavior of the MBTA if ridership increases by 20%.

  • A user is required to watch video training sessions as part of a recertification process and answer questions about them.

  • A user on a cooking website enters the number of dinner guests, and the cooking website adjusts all the recipes accordingly.

  • A user who had reserved a Zipcar arrives to find it has not been returned yet, and customer service transfers her reservation to an available car.

  • A computer game allows the user to take the role of a unit commander or general at Gettysburg and simulates the battle based on his or her commands.

  • A user searches for her reservation on a hotel website, and changes the arrival date and room type.

  var Person = function () {};

Creating an Object with a constructor

Using the Object() syntax, we can create an instance of our Person object using the constructor

  var clark = new Person();
  var bruce = new Person();

When we instantiate an object that has a constructor function, the object with run whatever the constructor function dictates

var Superhero = function () {
    console.log('Superhero instance created');
};

var clark = new Superhero(); 
    // console logs "Superhero instance created"

var bruce = new Superhero(); 
    // console logs "Superhero instance created"

Properties can be set in the constructor, so they are set specifically for each instance. This simply means that we pass them as parameters in our constructor function.

 var Superhero = function (firstName, superheroName) {
    // Important to understand here that the object 
    // properties firstName and superheroName
    // are set through the this keyword with the 
    // value passed through the constructor function

    this.firstName = firstName;
    this.superheroName = superheroName;
    console.log('Superhero instantiated');
  };

  var superman = new Superhero('Clark', 'Superman');
  console.log(superman.firstNAme + ' is ' + superman.superheroName);

Methods

  Superhero.prototype.identity = function() {
    console.log(this.firstName + ' is ' +this.superheroName);
  }

  var superman = new Person('Clark', 'Superman');
  superman.identity();

Wait.. uhh.. whats Prototype??

Every object in JavaScript has a prototype, connected to the constructor that created it.

IF JS finds doSomthing() as a function on ourObject, it runs that function

ourObject.doSomething()

If not, it looks to the master Object prototype to see if that function is attached to ALL objects

Restricting Access to Attributes

// Example 3

Person.prototype.setAge = function (newAge) {
  if (newAge < 0) {
    console.error("A person cannot be negative years old!");
  }
  else if (newAge > 150) {
    console.error("People do not generally live to the age of 150");
  }
  else {
    this.age = newAge;
  }
};

Person.prototype.getAge = function () {
  return this.age;
};

Monkey Exercise 

Open the monkey.js file in the starter code.

 

Work with a partner to create a monkey object, which has the following properties: name, species, foodsEaten

And the following methods:

  • eatSomething(thingAsString)
  • introduce: producers a string introducing itself, including its name, species, and what it's eaten.

 

Create 3 monkeys total. Make sure all 3 monkeys have all properties set and methods defined.

 

Exercise your monkeys by retrieving their properties and using their methods. Practice using both syntaxes for retrieving properties (dot notation and brackets).

Introduction to
JavaScript Object Notation

JSON

JSON text-based data format that's based on JavaScript

Because it's text, and it looks like JavaScript, JSON is simultaneously both easy for humans to read and write AND easy for programs to parse and generate.

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}    

We use JSON objects to transfer data between applications and Javascript.

To keep everything consistent, all JSON code must follow a number of strict conventions :

  • Property names must be double-quoted strings.
  • Trailing commas are forbidden.
  • Leading zeroes are prohibited.
  • In numbers, a decimal point must be followed by at least one digit.
  • Most characters are allowed in strings; however, certain characters (such as ', ", \, and newline/tab) must be 'escaped' with a preceding backslash (\) in order to be read as characters (as opposed to JSON control code).
  • All strings must be double-quoted.
  • No comments!

Practice

Work individually or with a partner and follow instructions in the app.js file in the starter code for this week's lesson.

 

 

 

Review

Objects not only give us more superpowers for storing and manipulating our data, they help us better structure our code. JSON will also be an important structure from this point on. All of the data we'll be working with from APIs will be in the form of JSON.

  • Be able to code objects using constructors and prototypes.
  • Understand how JSON transfers data between programs.

Homework

Converting JSON

  • All of the instructions for this exercise are contained in the json-hw.js file, located in the starter code folder
  • Provide students with the json-hw.js file and have them read through the instructions and complete each of the challenges, typing their code directly into the file
  •  

 

Resources

Made with Slides.com