Skip to content

Instantly share code, notes, and snippets.

@jkaihsu
Created May 6, 2013 06:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkaihsu/5523699 to your computer and use it in GitHub Desktop.
Save jkaihsu/5523699 to your computer and use it in GitHub Desktop.

JavaScript CodeSchool


Objects

Create a new object

var toilet = new Object();

Create a new object with properties (shorthand)

var toilet = {tankCapacity: 4.8, brand: 'Sloan'}

Functions

  1. Created for object behavior
  2. Resuable pieces of code
  3. Can be stored in a variable

Declare a function

var flush = function() {
  console.log("clear out content");
}

Call a function

> flush();
clear our content

Declare a function with an argument

var fillTank = function(volume) {
	console.log("Filling tank with " + volume + " liters of water.")
}

Call a function with an argument

> fillTank(4.8);
Filling tank with 4.8 liters of water.

Methods

  1. An object property that happens to be a function
Add a method to the toilet object

toilet.flush = function() {
	console.log("clearing out contents")
}

> toilet.fluhs();
clearing out contents

Access a Property (this)

toliet.brand = "Sloan"
toliet.flush = function() {
	console.log("clearing out contents of " + this.brand);
}

> toliet.flush();
clearing out contents of Sloan

Specify your own (this)

toilet.flush.call( {brand: 'Delta'} )

Constructor Funciton

  1. Named with Uppercase
  2. Called with new
function Toilet(brand) {
	this.brand = brand;
	this.tankCapacity = 4.8;
}

var myToilet = new Toilet("Sloan");

Prototypes

  1. Similar to Inheritance
  2. An object in which other objects are based
Toilet.prototype.sanitize = function() {
	console.log("Sanitizing " + this.brand);
}

Calling a prototype

myToilet.sanitize();
> Sanitizing Sloan

1. JavaScript first look on the myToilet instance
2. Then switched to prototype
3. Can be overwritten by creating an instance

myToilet.sanitize = function() {
	console.log("Seeting fire to " + this.brand);
}
1. The original sanitize will never be called

Prototype Chaining

function FancyToilet(brand) {
	Toilet.call(this, brand);
	this.constructor = FancnyToilet;
}

FancyToilet.prototype = new Toilet();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment