Objects

Objects

  • Objects are just a way of grouping values together.
  • They work by associating property names (sometimes called "keys") with values.

The simplist way to make an object is using the object literal syntax:

var cat = {
  name: 'sprinkles',
  age: 2,
  gender: 'female'
};

In the example above, "name" is a property name, and "sprinkles" is the associated value.

Retrieving Values

You can retrieve values from objects using the "dereferencing operator". That's just a fancy way of saying use a dot.

var cat = {
  name: 'sprinkles',
  age: 2,
  gender: 'female'
};

log( cat.name );
log( cat.color );

Setting a value

  • Setting or changing a value is similar to retrieving a value.
  • If you reference a property that does not exist on the object when setting its value it will be created.

.

var truck = { type: 'fire' };
truck.type = "tow";
truck.name = "towmator";

log( truck.name );
log( truck.type + " truck" );

In operator

JavaScript's in operator allows you to test whether a property exist on an object. The expression returns a boolean

var product = { 
    category: 'shoes', 
    brand: 'nike' 
};

log( "brand" in product );
log( "price" in product );

Deleting properties

JavaScript's delete operator allows you to remove a property from an object

var tv = { 
    highDef: true,
    wideScreen: true, 
    remote: "missing" 
};
log( tv.remote );
log( "remote" in tv );

delete tv.remote;

log( tv.remote );
log( "remote" in tv );

Objects in Objects

Any value that can be put in a variable (which is to say any data value at all) can also be assigned to a property of an object. This includes other objects

var aManager = {
  name: 'Fred',
  position: 'TPM'
};

var aWorker = {
  name: 'Johnny',
  position: 'Software Engineer',
  boss: aManager
};

log( aWorker.boss.name );

Objects in Objects

The previous example could also be written like this:

var worker = {
  name: 'Johnny',
  position: 'Software Engineer',
  boss: {
    name: 'Fred',
    position: 'TPM'
  }
};

log( worker.boss.name );

Functions in Objects

You can also assign a function as an object's property.

var greet = function() {
  log('Hello!');
};

var worker = {
  name: 'Johnny',
  sayGreeting: greet
};

worker.sayGreeting();

Often, programmers call functions that are stored in objects "methods".

Functions in Objects

The previous example could also be written like this:

var worker = {
  name: 'Johnny',
  sayGreeting: function() {
    log('Hello!');
  }
};

worker.sayGreeting();

Objects: What's the point?

To organize your code.

  • Group similar data together.
  • Group data and the functions that work with them together.
  • "Namespace" your code. That just means stick all of your data and functions in an object so that someone else doesn't accidentally overwrite it.

We may talk more about organizing your code at the end of the class.

Objects: Built-In Objects

JavaScript comes with a bunch of objects built-in.

(demonstration)

Programming Topics: Graphs

Programming Topics: Graphs

A graph is made up of verticies (aka nodes) and edges.





Programming Topics: Trees

A tree is a graph that has no cycles.

Trees come so much in programming that there are some special terms we use when talking about them:

  • Root node
  • Leaf nodes
  • Sibling
  • Parent

The Document-Object Model

The Document-Object Model

The Document-Object Model is the 'glue' that connects Javascript to the data on web pages.

It consists of several different components for interacting with web pages, but the most important of these is the "element heirarchy", a tree which consists of "elements" (think HTML tags) and "text nodes".



graphic from Eloquent Javascript by Marijn Haverbeke

The document Object

There is a global object in Javascript called document that contains all of the data and methods that we need to work with the DOM.

Here are some of the most important features of the document object:

  • document.getElementById('some-element-id') // Gets a dom element by it's id
  • document.documentElement // The <html> element
  • document.body // The <body> element.
  • document.createElement('div') // Creates a new DOM element
  • document.createTextNode('Some random text.') // Creates a new text node.

Traversing the DOM

Once we have a DOM element (either document.body or one that we have found using document.getElementById()), we can traverse the dom tree using some properties that all element objects have.

  • el.parentNode
  • el.firstChild
  • el.lastChild
  • el.nextSibling
  • el.previousSibling
  • el.childNodes (An array of nodes that are immediate children of el. We'll talk more about arrays after the midterm.)

Manipulating DOM Elements

Once we have a DOM element, we can use them to manipulate the web page! Most element attributes can be accessed directly by name on the object. Test Link

var linkEl = document.getElementById('aLink');
log( linkEl.href );

linkEl.href = 'http://creativecircus.edu';
log( linkEl.href );

There are a few special attributes as well.

  • el.className = 'highlighted'; // "class" is a reserved word
  • el.style // Another object. Use it to set CSS styles!

.

var linkEl = document.getElementById('aLink');
linkEl.style.color = '#ff0000';

Adding Elements

We can also add new children to an element.

The content will go here:


var myDiv = document.getElementById('myDiv');

// First we have to make the new element
var newChild = document.createElement('p');

// Then we need to make a new text node
var text = document.createTextNode('Lorem ipsum dolor sit amet.');

// Then we add the new text node to the new element.
newChild.appendChild( text );

// Then we add the new node to the page.
myDiv.appendChild( newChild );

Adding Elements (cont.)

Obviously this can be a pain really quick if you're adding a lot of elements to a page. There is a (usually) slower, but easier to read:

The content will go here:


var myDiv = document.getElementById('myDiv2');

myDiv.innerHTML = '<p>Lorem ipsum dolor sit amet.</p>';