Javascript has two very important chains

Prototype-chain

Scope-chain

Object-oriented programming in JS

Objects in JS

How do you create objects in JS?


var LivingEntity = function(location){
  this.x = location.x;
  this.y = location.y;
  this.z = location.z;
};
              

Adding methods?


var dog = new LivingEntity({
  x: 5,
  y: 0,
  z: 1
});

dog.moveWest = function(){
  this.x--;
};
            

Don't do this!

Unnecessary anonymous functions!


LivingEntity.prototype.moveWest = function(){
  this.x--;
}
            

Do this!

Takes advantage of the prototype chain!

The functions defined on the prototype chain only exist once, and references to them are passed around.

What is the prototype chain?

Each object has a prototype, even the object that exists in another object's prototype attribute.

How do you inherit from a superclass


var Dragon = function(location){
  LivingEntity.call(this, location);
  this.canFly = true;
};

Dragon.prototype = Object.create(LivingEntity.prototype);

Dragon.prototype.constructor = Dragon;

Dragon.prototype.fly = function(y){
  this.y += y;
};

var sparky = new Dragon({
  x: 0,
  y: 0,
  z: 0
});
          

What does the prototype-chain look like?

sparky sparky.__proto__
x, y, z, canFly fly
sparky.__proto__.__proto__ sparky.__proto__.__proto__.__proto__
moveWest create, toString, etc...

What happens when I call a method on an object?

The object is checked, then the prototype chain is traversed until that method is found.

Anonymous functions

The root of the problem: Functions have a state!

Closure


var helloStr = 'world';
var sayHello = function(name){
  return function(){
    console.log('Hello ' + name + '!');
  }
}
var sayGreeting = sayHello(helloStr);
//woops, I meant to greet Bob
helloStr = 'Bob';
sayGreeting();
            
Output

Hello world!
              
What about this?

for (var i = 0; i < 10; i++){
  setTimeout(function(){
    console.log(i);
  }, 1000);
}
            
Output

10
10
10
10
10
10
10
10
10
10
              

What is scope?

Javascript has function scope

Scope Properties

{
  _scope,
  variables
}
          

How are closures related to the scope chain?

When a variable is used, the scope chain is traversed to find the first time the variable was declared

Doing closure right


var logI = function(i){
  return function(){
    console.log(i);
  }
};
for (var i = 0; i < 10; i++){
  setTimeout(logI(i), 1000);
}
          

IIFE

Immediately Invoked Functional Expression

(function(global){
  var privateVariable = 'No one can ever see me or change me';

  global.getPrivateVariable = function(){
    return privateVariable;
  };
})(window);