Object Oriented JavaScript Part 1

David Tang / ITP 404 / 2015

What are Objects?

Objects are containers for a collection of related variables (properties) and functions (methods)

document

window

document.URL
document.getElementById()
document.getElementsByTagName()
document.querySelector()
window.alert()
window.parseFloat()
window.parseInt()
window.document == document

When accessing a global variable, window is implied

Object Literals

var cat = {
  name: 'Fiona',
  age: 1.5,
  'for': 'David',
  siblings: ['Chestnut', 'Biscuit']
};

Object keys must:

  • start with a letter, dollar sign, or underscore
  • only contain alphanumeric characters, underscores, and dollar signs
  • cannot be a reserved word in JS
  • If you must use a reserved word or a special character for the key name, you must put the key in quotes

Object keys can contain:

  • strings
  • numbers
  • booleans
  • arrays
  • functions
  • other objects

Read properties

Change properties

var cat = {
  name: 'Fiona',
  age: 1.5,
  siblings: ['Chestnut', 'Biscuit']
};

console.log(cat.name); // Fiona
cat.name = 'Chestnut';
cat.color = 'white';

Write properties

Dot Notation

var cat = {
  name: 'Fiona',
  age: 1.5,
  siblings: ['Chestnut', 'Biscuit'],
  meow: function() {
    console.log(cat.name);
  }
};
cat.meow();
var cat = {
  name: 'Fiona',
  age: 1.5,
  siblings: ['Chestnut', 'Biscuit'],
  meow: function() {
    console.log(this.name); // Fiona
  }
};

"this"

Methods

function getTweets(user, count, startDate, stopDate) {
  // the order of these params might be hard to remember
}

getTweets('BurnNoticeUSA', 10, '2013-05-12', '2013-09-22');

Objects as function arguments

eliminates the need to specify the function arguments in a specific order

function getTweets(properties) {
  // properties.user
  // properties.count
}

getTweets({
  stopDate: '2013-09-22',
  count: 10,
  startDate: '2013-05-12',
  user: 'BurnNoticeUSA'
});

Bracket Notation

var config = {
  url: 'some-url-here',
  apiKey: '90399492',
  ajaxRoute: 'some-ajax-route'
};

config['url'];
config['apiKey'];
var apiKey = 'apiKey';
config[apiKey];

variable as a key

Bracket Notation

var searchCache = {};

function search(term) {
  var results;

  if (searchCache[term]) {
    return searchCache[term];
  } else {
    results = getResults(term);
    searchCache[term] = results;
    return results;
  }
}

For...in Loop

var config = {
  url: 'some-url-here',
  apiKey: '90399492',
  ajaxRoute: 'some-ajax-route'
};

for (var key in config) {
  console.log(key, config[key])
}

// url, 'some-url-here'
// apiKey, '90399492'
// ajaxRoute: 'some-ajax-route'

Namespacing

var APP = {
  Utils: {}
};

APP.Utils.log = function() { /* implementation */ };
APP.Utils.isNumber = function() { /* implementation */ };
APP.Player = {
  playlist: [ /* list of songs here */ ],
  play: function(song) { /* implementation */ },
  pause: function(song) { /* implementation */ },
  stop: function(song) { /* implementation */ }
};

organize units of code using nested object literals, similar to a directory structure, or packages in other languages

create self-contained units that represent different widgets on the page or modules

'this'

var cat = {
  name: 'Fiona',
  age: 1.5,
  siblings: ['Chestnut', 'Biscuit'],
  meow: function() {
    console.log(this.name); // Fiona
  }
};

The value of 'this' is determined when a function is invoked

There are a few rules to follow to determine what this is.

1st Rule for 'this'

function hi() {
    console.log(this);
}

hi(); // window

Simple function calls

2nd Rule for 'this'

var cat = {
  name: 'Fiona',
  age: 1.5,
  siblings: ['Chestnut', 'Biscuit'],
  meow: function() {
    console.log(this.name); // Fiona
  }
};

cat.meow();

Method calls on objects

2nd Rule for 'this'

var person = {
    hi: function() {
        function hi2() {
            console.log(this);
        }

        hi2();

        console.log(this);
    }
};

person.hi();

Method calls on objects

What will be logged?

// window
// person

2nd Rule for 'this'

var person = {};

function hi() {
    console.log(this);
}

person.hi = hi;

Method calls on objects

person.hi();
hi();

What is this?

// person
// window

Remember, 'this' is determined when a function is called

More Rules

  • The "new" operator
  • Function.prototype.call()
  • Function.prototype.apply()
  • Function.prototype.bind()

We will look at these later in the semester

jQuery and 'this'

$('#save').on('click', function() {
    // 'this' refers to the save button DOM node with an id of 'save'
    // 'this' is the same as document.getElementById('save')
    // 'this' is the same as document.querySelector('#save')
});

jQuery manipulates what 'this' refers to for your convenience

var Form = {
    setup: function() {
        this.validateForm();

        $('#save').on('click', function() {
            // how do I call validateForm here?
        });
    },

    validateForm: function() {

    }
};

Form.setup();
var Form = {
    setup: function() {
        var self = this;

        $('#save').on('click', function() {
            self.validateForm();
        });
    },

    validateForm: function() {

    }
};

Form.setup();

Demo

deck

By David Tang

deck

  • 693
Loading comments...

More from David Tang