object

constructors

Class overview

  • Homework Solution
  • Object Constructors
  • Constructor arguments
  • This
  • Explicit return statements
  • Closures
  • Homework Overview

OBJECT CONSTRUCTORS

  • Allow you to create reproducible Objects
  • Can use instanceof to check Object type
  • Perfect for Objects that hold state
  • Enables use of the 'this' keyword inside a function
  • Used when you are creating a multiple objects that will have the same structure but different contents.
 
//constructor declarationfunction CustomObject() {};//using constructor to create an objectvar myObj = new CustomObject();myObj instanceof CustomObject;// > true

object constructors

  • OOP Concept shoe-horned into JavaScript
  • New objects initiated with the 'new' keyword & constructor function call.
 //declare constructor function function MyObject() { } //create object with constructor var myObj = new MyObject();
  • Inside the constructor function, attach properties to the returning object by using the 'this' keyword.

MDN Object Reference

object constructor arguments

  • In OOP languages, constructor arguments are used to establish initial state for an object.
  • In JavaScript, concept is the same, but implementation is weirder.
  • Useful when using remote data to build custom objects.
 //constructor declaration with constructor arguments function MyObject(dataObj) {     this.data = dataObj; } //use the arguments like this: var myObj = new MyObject({items : 4}); console.log(myObj.data.items); // > 4

THIS

  • Reserved keyword
  • The 'this' variable always refers to the current object.
  • Works in functions that are constructors, but not normal functions.
 

explicit object return

  • By default, constructors return the built object. 
  • By adding an explicit return statement, you can control what is returned when a constructor is called.
 function MyObject() {   return {     items : 3,     count : function(num) {        console.log(num);     }   } }




closure

  • Specially designed function that creates a function & a context.
  • Simulates private properties.
  • Useful for building dynamic functions.
 function closureFunction() {   var closureVar = 'I come from a closure!';   function printOut() {     console.log(closureVar);   }   return printOut; }
var closFunc = new closureFunction; closFunc();
MDN Closure Reference

todomvc

Example website building a simple task with many different JavaScript MVC frameworks.
Made with Slides.com