Object-Oriented JavaScript

"I think if one wants to make real progress in JS one needs to drag one's class-based-OO self out back and beat him to death." - Steve Conover

Object vs. Object

Definition of Object

True Object-Oriented Programming

"this" is it

...but "this" isn't always it

"this" and callbacks

TODO

apply Yourself

A Million Ways To Make An Object

Making an object from scratch

var circle = {};
circle.radius = 2;
circle.circumference = function() {
    return Math.PI * 2 * this.radius;
}
circle.area = function() {
    return Math.PI * this.radius * this.radius;
}
circle.radius; // 2
circle.area;   // function () { ...
circle.area(); // 12.566370614359172

Making an object from scratch, with literals

var circle = {
    radius: 2,
    circumference: function() {
        return Math.PI * 2 * this.radius;
    },
    area: function() {
        return Math.PI * this.radius * this.radius;
    }
}
circle.radius; // 2
circle.area;   // function () { ...
circle.area(); // 12.566370614359172

Constructors and "new"

Making an object with a constructor

var Circle = function(radius) {
    this.radius = radius;
    this.circumference = function() {
        return Math.PI * 2 * this.radius;
    }
    this.area = function() {
        return Math.PI * this.radius * this.radius;
    }
};
var circle = new Circle(2);
circle.radius; // 2
circle.area;   // function () { ...
circle.area(); // 12.566370614359172

Making an object with private data using closures

You can also make private methods using closures

var Circle = function(radius) {
    var rSquared = function {
        return radius * radius;
    }
    this.circumference = function() {
        return Math.PI * 2 * radius;
    }
    this.area = function() {
        return Math.PI * rSquared();
    }
};

A digression: Getters and Setters

Prototypes

Using new to set an object's prototype

When is a prototype not a prototype?

Names and Types

Using prototypes to extend core objects

Prototypical Inheritance

Calling superclass methods

Disposable Function

extend

Resources

The Fine Print

This work is copyright (C) 2010-2011 by Alex Chaffee. All rights reserved. Permission is granted to use this material for non-profit educational purposes, including self-education and open workshops. Use by educational institutions or for-profit classes must be licensed. For permission, please contact Alex Chaffee at alex@stinky.com.

Next: Node >> << Previous: Ajax

Outline

[contents]

Object Oriented Javascript Slides - Code Like This

/

#