Skip to content

Instantly share code, notes, and snippets.

@rob0t7
Created November 2, 2016 17:29
Show Gist options
  • Save rob0t7/cc5a96c5101827e3251758da8ab0cb0c to your computer and use it in GitHub Desktop.
Save rob0t7/cc5a96c5101827e3251758da8ab0cb0c to your computer and use it in GitHub Desktop.
Intro To JS Objects

Javascript Objects

Our agenda for today includes:

  • recap of scopes (covered yesterday)
  • AssociativeArrays (i.e. JS objects, Hash in Ruby, Dict in Python, HastTable in Java)
  • Using associate arrays with arrays
  • JS context (when executing a function) which can either be set
    • when creating a object using new
    • implicitly when calling a function that is a property of an object
    • explicitly set using apply, call, bind

Primitive JS Types

JS has some primitive types that you can use when you program. They include:

  • Number: 1, 1.4, 2e10
  • Boolean: true, false
  • String: 'Hello Word!'
  • undefined (considered to evaluate to falsey)
  • null (evaluates as falsey)
  • NaN

We also learn about Arrays that allow us to store a list of objects in a sorted order.

To find the type of an object you can use typeof()

Associative Arrays (i.e. JS Objects)

Today we learn about Associative Arrays (from now on we will call the colloqually Objects). This datatype allows us to store key-value pairs of information. This allows us to create richer data structures composed of other objects and primitive data types. The keys of objects are always converted to strings and the values can be any data type in JS (even functions).

// List of friends composed of different datatypes
var myFriends = [
  {
    name: 'Jill',
    phone: '416-453-4533',
    sex: 'female'
  },
  {
    name: 'Bob',
    phone: '342-545-2345',
    sex: 'male'
  },
  {
    name: 'Tom',
    phone: '343-234-2342',
    sex: 'male'
  }
]

// fetches all the males
function fetchMales(contactList) {
  var output = []
  contactList.forEach(function(contact) {
    if (contact.sex === 'male') {
      output.push(contact)
    }
  })

  // can also traverse the array using a for loop
  //for(var i = 0; i < contactList.length; i++) {
  //  if (contactList[i].sex === 'male') {
  //    output += contactList[i]
  //  }
  //}
  return output;
}
fetchMales(myFriends) === [
                            {
                              name: 'Bob',
                              phone: '342-545-2345',
                              sex: 'male'
                            },
                            {
                              name: 'Tom',
                              phone: '343-234-2342',
                              sex: 'male'
                            }
                          ]

// we could also access properties of an object using the *[]*
notation
function filterContactsByAttr(contactList, attr, attrValue) {
  var output = []
  contactList.forEach(function(contact) {
    if (contact[attr] === attrValue) {
      output.push(contact)
    }
  })
  return output
}
fitlerContactsByAttr(myFriends, 'sex', 'female') = [{
                                                      name: 'Jill',
                                                      phone: '416-453-4533',
                                                      sex: 'female'
                                                    }]

We can also create more complex objects! We can also attach functions to objects

var me = {
  name: 'rob jackiewicz',
  email: '[email protected]',
  hobbies: ['beer', 'javascript', 'eating'],
  friends: myFriends
  printFemaleFriends: function() {
    return this.friends.filter(function(friend) {
      friend.sex == 'female'
    })
  }
}

me.printFemaleFriends() === [ {name: 'Jill', phone: '416-453-4533',
sex: 'female'} ]

THIS (function context)

We now get to the topic of this.

When a function runs it can access variables in that are available in its scope but the function also has the context that is running it that can be referenced as this

function foo() {
  return this
}

// By default in the browser the global context that runs the function
above is the object window
foo() === window

The next example the object referenced by this will by the object that contains the function. It will be set implicitly since it is the person object that is call the function. HINT Most trivial cases this is bound to the object left of the '.' when the function is being called, so in this case this === person since 'person' is left of the dot.

var person = {
  name: 'Bob',
  sayHello: function() {
    console.log("Hi, my name is " + this.name)
  }
}

person.sayHello()

Finally we can explicitly set this to be another value using apply, call, and bind.

// assume the code above exists

function dance(dancemove) {
  console.log(this.name + "is doing the" + dancemove + "move.");
}

dance('shuffle') // fails since window.name does not exist (output is "undefined is doing the shuffle move.")
dance.call(person, 'shuffle') // output = "Bob is doing the shuffle move."
dance.apply(person, ['shuffle']) // same output as above. Notice that the arguments are now in an array

dance = dance.bind(person)
dance('shuffle') // output = "Bob is doing the shuffle move"
// Bind returns a new function where 'this' is explicitly bound.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment