Create a new object
var toilet = new Object();
Create a new object with properties (shorthand)
var toilet = {tankCapacity: 4.8, brand: 'Sloan'}
- Created for object behavior
- Resuable pieces of code
- 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
- 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'} )
- Named with Uppercase
- Called with new
function Toilet(brand) {
this.brand = brand;
this.tankCapacity = 4.8;
}
var myToilet = new Toilet("Sloan");
- Similar to Inheritance
- 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();