Wednesday, August 5, 2015

How To Optimize Your Site With HTTP Caching




Thanks to Kalid Azad


I’ve been on a web tweaking kick lately: how to speed up your javascript, gzip files with your server, and know how to set up caching. But the reason is simple: site performance is a feature.
For web sites, speed may be feature #1. Users hate waiting, we get frustrated by buffering videos and pages that pop together as images slowly load. It’s a jarring (aka bad) user experience. Time invested in site optimization is well worth it, so let’s dive in.

What is Caching?

Caching is a great example of the ubiquitous time-space tradeoff in programming. You can save time by using space to store results.
In the case of websites, the browser can save a copy of images, stylesheets, javascript or the entire page. The next time the user needs that resource (such as a script or logo that appears on every page), the browser doesn’t have to download it again. Fewer downloads means a faster, happier site.
Here’s a quick refresher on how a web browser gets a page from the server:
HTTP_request.png
  1. Browser: Yo! You got index.html?
  2. Server: (Looking it up…)
  3. Sever: Totally, dude! It’s right here!
  4. Browser: That’s rad, I’m downloading it now and showing the user.
(The actual HTTP protocol may have minor differences; see Live HTTP Headers for more details.)

Caching’s Ugly Secret: It Gets Stale

Caching seems fun and easy. The browser saves a copy of a file (like a logo image) and uses this cached (saved) copy on each page that needs the logo. This avoids having to download the image ever again and is perfect, right?
Wrongo. What happens when the company logo changes? Amazon.com becomes Nile.com? Google becomes Quadrillion?
We’ve got a problem. The shiny new logo needs to go with the shiny new site, caches be damned.
So even though the browser has the logo, it doesn’t know whether the image can be used. After all, the file may have changed on the server and there could be an updated version.
So why bother caching if we can’t be sure if the file is good? Luckily, there’s a few ways to fix this problem.

Caching Method 1: Last-Modified

One fix is for the server to tell the browser what version of the file it is sending. A server can return a Last-modified date along with the file (let’s call it logo.png), like this:
Last-modified: Fri, 16 Mar 2007 04:00:25 GMT File Contents (could be an image, HTML, CSS, Javascript...)
Now the browser knows that the file it got (logo.png) was created on Mar 16 2007. The next time the browser needs logo.png, it can do a special check with the server:
HTTP-caching-last-modified_1.png
  1. Browser: Hey, give me logo.png, but only if it’s been modified since Mar 16, 2007.
  2. Server: (Checking the modification date)
  3. Server: Hey, you’re in luck! It was not modified since that date. You have the latest version.
  4. Browser: Great! I’ll show the user the cached version.
Sending the short “Not Modified” message is a lot faster than needing to download the file again, especially for giant javascript or image files. Caching saves the day (err… the bandwidth).

Caching Method 2: ETag

Comparing versions with the modification time generally works, but could lead to problems. What if the server’s clock was originally wrong and then got fixed? What if daylight savings time comes early and the server isn’t updated? The caches could be inaccurate.
ETags to the rescue. An ETag is a unique identifier given to every file. It’s like a hash or fingerprint: every file gets a unique fingerprint, and if you change the file (even by one byte), the fingerprint changes as well.
Instead of sending back the modification time, the server can send back the ETag (fingerprint):
ETag: ead145f File Contents (could be an image, HTML, CSS, Javascript...)
The ETag can be any string which uniquely identifies the file. The next time the browser needs logo.png, it can have a conversation like this:
HTTP_caching_if_none_match.png
  1. Browser: Can I get logo.png, if nothing matches tag “ead145f”?
  2. Server: (Checking fingerprint on logo.png)
  3. Server: You’re in luck! The version here is “ead145f”. It was not modified.
  4. Browser: Score! I’ll show the user my cached version.
Just like last-modifed, ETags solve the problem of comparing file versions, except that “if-none-match” is a bit harder to work into a sentence than “if-modified-since”. But that’s my problem, not yours. ETags work great.

Caching Method 3: Expires

Caching a file and checking with the server is nice, except for one thing: we are still checking with the server. It’s like analyzing your milk every time you make cereal to see whether it’s safe to drink. Sure, it’s better than buying a new gallon each time, but it’s not exactly wonderful.
And how do we handle this milk situation? With an expiration date!
If we know when the milk (logo.png) expires, we keep using it until that date (and maybe a few days longer, if you’re a college student). As soon as it goes expires, we contact the server for a fresh copy, with a new expiration date. The header looks like this:
Expires: Tue, 20 Mar 2007 04:00:25 GMT File Contents (could be an image, HTML, CSS, Javascript...)
In the meantime, we avoid even talking to the server if we’re in the expiration period:
HTTP_caching_expires.png
There isn’t a conversation here; the browser has a monologue.
  1. Browser: Self, is it before the expiration date of Mar 20, 2007? (Assume it is).
  2. Browser: Verily, I will show the user the cached version.
And that’s that. The web server didn’t have to do anything. The user sees the file instantly.

Caching Method 4: Max-Age

Oh, we’re not done yet. Expires is great, but it has to be computed for every date. The max-age header lets us say “This file expires 1 week from today”, which is simpler than setting an explicit date.
Max-Age is measured in seconds. Here’s a few quick second conversions:
  • 1 day in seconds = 86400
  • 1 week in seconds = 604800
  • 1 month in seconds = 2629000
  • 1 year in seconds = 31536000 (effectively infinite on internet time)

Bonus Header: Public and Private

The cache headers never cease. Sometimes a server needs to control when certain resources are cached.
  • Cache-control: public means the cached version can be saved by proxies and other intermediate servers, where everyone can see it.
  • Cache-control: private means the file is different for different users (such as their personal homepage). The user’s private browser can cache it, but not public proxies.
  • Cache-control: no-cache means the file should not be cached. This is useful for things like search results where the URL appears the same but the content may change.
However, be wary that some cache directives only work on newer HTTP 1.1 browsers. If you are doing special caching of authenticated pages then read more about caching.

Ok, I’m Sold: Enable Caching

First, make sure Apache has mod_headers and mod_expires enabled:
... list your current modules...
apachectl -t -D DUMP_MODULES

... enable headers and expires if not in the list above...
a2enmod headers
a2enmod expires
The general format for setting headers is
  • File types to match
  • Header / Expiration to set
A general tip: the less a resource changes (images, pdfs, etc.) the longer you should cache it. If it never changes (every version has a different URL) then cache it for as long as you can (i.e. a year)!
One technique: Have a loader file (index.html) which is not cached, but that knows the locations of the items which are cached permanently. The user will always get the loader file, but may have already cached the resources it points to.
The following config settings are based on the ones at AskApache.
Seconds Calculator
All the times are given in seconds (A0 = Access + 0 seconds).
Using Expires Headers
ExpiresActive On
ExpiresDefault A0

# 1 YEAR - doesn't change often
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
ExpiresDefault A31536000
</FilesMatch>

# 1 WEEK - possible to be changed, unlikely
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
ExpiresDefault A604800
</FilesMatch>

# 3 HOUR - core content, changes quickly
<FilesMatch "\.(txt|xml|js|css)$">
ExpiresDefault A10800
</FilesMatch>
Again, if you know certain content (like javascript) won’t be changing often, have “js” files expire after a week.
Using max-age headers:
# 1 YEAR
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>

# 3 HOUR
<FilesMatch "\.(txt|xml|js|css)$">
Header set Cache-Control "max-age=10800"
</FilesMatch>

# NEVER CACHE - notice the extra directives
<FilesMatch "\.(html|htm|php|cgi|pl)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>

Final Step: Check Your Caching

To see whether your files are cached, do the following:
  • Online: Examine your site in Redbot (You’ll see the headers returned, and a cache summary on the side)
  • In Browser: Use FireBug or Live HTTP Headers to see the HTTP response (304 Not Modified, Cache-Control, etc.). In particular, I’ll load a page and use Live HTTP Headers to make sure no packets are being sent to load images, logos, and other cached files. If you press ctrl+refresh the browser will force a reload of all files.
Read more about caching, or the HTTP header fields. Caching doesn’t help with the initial download (that’s what gzip is for), but it makes the overall site experience much better.
Remember: Creating unique URLs is the simplest way to caching heaven. Have fun streamlining your site!

Tuesday, August 4, 2015

Javascript Constructors and Prototypes


?

If you didn’t already know, Javascript functions double as object constructors. For example, to simulate a class in object-oriented programming, you would write
function Person(name){
    this.name = name
}

Anyway, now that you have a function, you’d use the new statement to create a Person
var bob = new Person('Bob')
// {name: 'Bob'}
Just to be sure that bob is indeed a Person, we can ask
bob instanceof Person
// true
You could also call Person as a function - without the new,
Person('Bob')
// undefined
but that just returns undefined. Also, you really don’t want to do this, because you’ve just unintentionally created a name global variable
name
// 'Bob'
Uh… that’s not good, especially if I already had a variable called name, it would have been overwritten. The reason this happens is because when you call a function as a function(without new), this is set to the global object - in the browser, this is the window object, see
window.name
// 'Bob'
this === window
// true
So… if you want to write a constructor, use it like a constructor, if you want to write a function, use it like a function, don’t mix and match.
Someone pointed out though, that you can prevent this polluting of the namespace(those are just big words for creating global variables) by using this trick
function Person(name){
    if (!(this instanceof Person))
        return new Person(name)
    this.name = name
}
What this does is:
  1. Check whether this is really a Person - which it would be if called using new.
  2. If it indeed is a Person, go on your merry way.
  3. If it is not a Person, use a new to create a Person - the correct way, and return it.
This allows calling it as a function to return a Person, and it doesn’t pollute the namespace.
Person('Bob')
// {name: 'Bob'}
name
// undefined
But what is surprising is that calling it with new still works too
new Person('Bob')
// {name: 'Bob'}
Why? It turns out that if you return a value in a constructor, Javascript will honor it, and return it as the newly created object when you use a new. But, you might be thinking, can I return a non-Person? That would be kind of like lying.
function Cat(name){
    this.name = name
}
function Person(name){
    return new Cat(name)
}
var bob = new Person('Bob')
bob instanceof Person
// false
bob instanceof Cat
// true
So, I ask for a Person and I get a Cat? Well, in Javascript it can happen. You can even return an Array.
function Person(name){
    return [name]
}
new Person('Bob')
// ['Bob']
There are limits to this madness though: if you return a value of a primitive type, this won’t work.
function Person(name){
    this.name = name
    return 5
}
new Person('Bob')
// {name: 'Bob'}
Number, String, Boolean, Date are all primitive types. If you return one of these types of values from a constructor, it would be ignored and the constructor would go back to its normal behavior of returning the this object.

Methods

In the beginning, I said that functions double as constructors, well, actually, they more like triple. Functions also act as methods.
If you know OOP, you know that methods are the behaviors of the object - what the object can do. In Javascript, methods are just functions attached to an object - you can create methods simply by creating functions and assigning them to the object
function Person(name){
    this.name = name
    this.sayHi = function(){
        return 'Hi, I am ' + this.name
    }
}
Bob can now say “Hi”
var bob = new Person('Bob')
bob.sayHi()
// 'Hi, I am Bob'
Actually, we can attach methods to objects without even bothering with this constructor crap and instead create an object out right
var bob = {name: 'Bob'} // this is a Javascript object!
bob.sayHi = function(){
    return 'Hi, I am ' + this.name
}
This would work just as well. Or, if you prefer, write it as one big object
var bob = {
    name: 'Bob',
    sayHi: function(){
        return 'Hi, I am ' + this.name
    }
}
So, why are we bothering with constructors in the first place? Answer: inheritance.

Inheritance and the Prototype

Right, so inheritance. You know inheritance, right? You know how in Java, for example, you can have one class inherit another and automatically get all the methods and variables of the parent class?
public class Mammal{
    public void breathe(){
        // do some breathing
    }
}
public class Cat extends Mammal{
    // now cat too can breathe!
}
Well, in Javascript, we have the same thing, just different. For starters, we don’t even have classes! Instead, we have something called the prototype. Here’s how we write the equivalent of the above Java code in Javascript
function Mammal(){
}
Mammal.prototype.breathe = function(){
    // do some breathing
}
function Cat(){
}
Cat.prototype = new Mammal()
Cat.prototype.constructor = Cat
// now cat too can breathe!
What’s this prototype? That’s just a bunch of gibberish!
Javascript is different from traditional object-oriented languages in that it uses prototype inheritance. In a nutshell, prototype inheritance in Javascript works like this:
  1. An object has a number of properties. This includes any attributes or functions(methods).
  2. An object has a special parent property, this is also called the prototype of the object(__proto__). An object inherits all the properties of its parent.
  3. An object can override a property of its parent by setting the property on itself.
  4. A constructor creates objects. Each constructor has an associated prototype object, which is simply another object.
  5. When an object is created, it’s parent is set to the prototype object associated with the constructor that created it.
Okay! Now that you understand everything there is to know about prototype inheritance, let’s look at our Cat example more closely and break it down.
First, we create a constructor for Mammal
function Mammal(){
}
At this point, Mammal already has an associated prototype
Mammal.prototype
// {}
Let’s create an instance
var mammal = new Mammal()
Now, let’s verify the second law of prototype inheritence(it’s just the second bullet from the list)
mammal.__proto__ === Mammal.prototype
// true
Next, we add the breathe function to the prototype of Mammal
Mammal.prototype.breathe = function(){
    // do some breathing
}
At this point, mammal the instance can breathe
mammal.breathe()
because it inherits from Mammal.prototype. Next,
function Cat(){
}
Cat.prototype = new Mammal()
Cat constructor is created and we set Cat.prototype to a new instance of Mammal. Why do we do this?
var garfield = new Cat()
garfield.breathe()
because now any cat instance inherits Mammal and will therefore be able to breathe as well. Next,
Cat.prototype.constructor = Cat
Ensures that cats know that they are cats:
garfield.__proto__ === Cat.prototype
// true
Cat.prototype.constructor === Cat
// true
garfield instanceof Cat
// true
Each time you create a new instance of Cat, you create a 2-level chain, in that garfield is now parented by Cat.prototype which, since it is an instance of Mammal, is in turn parented by Mammal.prototype.
Now, guess who’s the parent of Mammal.prototype? Yeah, you guessed it, Object.prototype. So actually, it’s a 3-level chain
garfield -> Cat.prototype -> Mammal.prototype -> Object.prototype
You can add properties to any of garfield’s parents, and garfield would magically gain those properties too, even after garfield has already been created!
Cat.prototype.isCat = true
Mammal.prototype.isMammal = true
Object.prototype.isObject = true
garfield.isCat // true
garfield.isMammal // true
garfield.isObject // true
You can ask whether he has a given property
'isMammal' in garfield
// true
and you can also distinguish between own properties vs inherited properties
garfield.name = 'Garfield'
garfield.hasOwnProperty('name')
// true
garfield.hasOwnProperty('breathe')
// false

Setting Methods on the Prototype

Now that you really understand prototypes, let’s go back to the very first example of defining methods on objects
function Person(name){
    this.name = name
    this.sayHi = function(){
        return 'Hi, I am ' + this.name
    }
}
This is actually not the optimal way to do it. A better way is to define the method on Person.prototype
function Person(name){
    this.name = name
}
Person.prototype.sayHi = function(){
    return 'Hi, I am ' + this.name
}
Why is this better? Anyone? Anyone? Beuller?
In the first version, each time you create a person, a new sayHi function will be created for him, where as in the second version, only one sayHi function is ever created, and is shared amongst all persons that are created - because Person.prototype is their parent. Thus, declaring methods on the prototype is more memory efficient.

Apply and Call

As you can see, functions become methods just by virtue of being attached to objects, at which point the this within that function refers to the object which it is attached to, right? Well… not exactly. Look at our previous example
function Person(name){
    this.name = name
}
Person.prototype.sayHi = function(){
    return 'Hi, I am ' + this.name
}
Now, if you create 2 people, jack and jill
var jack = new Person('Jack')
var jill = new Person('Jill')
jack.sayHi()
// 'Hi, I am Jack'
jill.sayHi()
// 'Hi, I am Jill'
Here, sayHi is not attached to jack or jill, rather, it’s attached to their prototype: Person.prototype. How does the function sayHi know jack and jill’s names?
Answer: this is not bound to any particular object until you call the function.
When you call jack.sayHi(), sayHi’s this will be bound to jack; when you call jill.sayHi(), it will be bound to jill instead, but binding does not change anything about the function itself - it’s still the same function!
It turns out that you can explicitly bind a function to an object yourself.
function sing(){
    return this.name + ' sings!'
}
sing.apply(jack)
// 'Jack sings!'
The apply method belongs to Function.prototype(yeah, that’s right, functions are objects and have prototypes too and can also have properties!). So, you can use apply with any function to call it while binding it to the object of your choosing, even if the function is not attached to it. In fact, you can even apply the method to an object of a different type
function Flower(name){
    this.name = name
}
var tulip = new Flower('Tulip')
jack.sayHi.apply(tulip)
// 'Hi, I am Tulip'
You might say
Wait a minute! A Tulip is not supposed to say hi!
To that, I would say
Everything is everybody. Everybody is everything. We all cool! Just…chill, man!
As long as the object has a name property, sayHi is happy to print it out. This is the principle of duck typing
If it quacks like a duck and it walks like a duck - it’s a duck to me.
I am sure I misquoted that, but whatever.
Now back to the apply function: if you want to include parameters you can pass them as an array as the second parameter to apply.
function singTo(other){
    return this.name + ' sings for ' + other.name
}
singTo.apply(jack, [jill])
// 'Jack sings for Jill'
Function.prototype also has a call function, which works very much like apply. The only difference is in that rather than passing the parameters as an array in the second parameter, you would just add them to the end:
sing.call(jack, jill)
// 'Jack sings for Jill'

The new method

Now, for something fun
apply is really handy for certain situations when you want to call a function with a variable list of arguments. For example, the Math.max function takes a variable number of arguments
Math.max(4, 1, 8, 9, 2)
// 9
This is nice, but it’s not generic. By using apply you can get the max for an arbitrary array,
Math.max.apply(Math, myarray)
Much more useful!
Now, given that apply is so useful, there may come times when you want to use it, but rather than call-as-function,
Math.max.apply(Math, args)
you want to call-as-constructor.
new Person.apply(Person, args)
Sadly, this doesn’t work. It’ll think you are calling Person.apply as a constructor. How about this
(new Person).apply(Person, args)
That doesn’t work either, because it will first construct a person, and then try calling the apply method on that person.
What to do? Thanks to an idea presented on this answer on StackOverflow, there is a way!
We can create a new method for Function.prototype.
Function.prototype.new = function(){
    var args = arguments
    var constructor = this
    function Fake(){
         constructor.apply(this, args)
    }
    Fake.prototype = constructor.prototype
    return new Fake
}
With this, we can call constructors with the new method rather than the new statement
var bob = Person.new('Bob')
Let’s go through how the new method works.
First,
var args = arguments
var constructor = this
function Fake(){
     constructor.apply(this, args)
}
we create a Fake constructor which will apply our real constructor as a method when created. In the context of the new method, this is the real constructor - we save it to be used in the Fake constructor. We also save the arguments with which new was called to reuse in the Fake constructor. Next,
Fake.prototype = constructor.prototype
we set Fake.prototype to the original constructor. Since the prototype’s constructor property is still set to the original constructor, any object created by Fake will still be an instanceof the original constructor. Finally,
return new Fake
Create the object using the Fake constructor and return it.
Did you get all that? It’s okay if you don’t get it the first time; just look it over and poke at it a few more times.
Anyways, the point of all of that was that now you can do things like
var children = [new Person('Ben'), new Person('Dan')]
var args = ['Bob'].concat(children)
var bob = Person.new.apply(Person, args)
Nice! But why do we have to write Person twice? We can probably write a helper method
Function.prototype.applyNew = function(){
     return this.new.apply(this, arguments)
}
So you can do
var bob = Person.applyNew(args)
Nice, slightly better!
What’s the point of this exercise anyway?
Well, it shows that Javascript is a flexible little language. Even if it doesn’t do the things you want, you can probably mold it into doing them.

Summary

This is the end of this lesson/article/blog post. It was nice having you! Today we learned about:
  1. Constructors
  2. Methods and Prototypes
  3. apply and call
  4. Implementing the new method

Monday, August 3, 2015

The Difference Between Call and Apply in Javascript

One very common thing that trips me up when writing Javascript is knowing when to use call and when to useapply. If you're wondering what these methods are, or don't know how scope works in JavaScript, then it might make sense to read the Javascript Fundamentals first.

Let's look at some ways we might want to use them:
var person1 = {name: 'Marvin', age: 42, size: '2xM'};
var person2 = {name: 'Zaphod', age: 42000000000, size: '1xS'};

var sayHello = function(){
    alert('Hello, ' + this.name);
};

var sayGoodbye = function(){
    alert('Goodbye, ' + this.name);
};
Now if you've read the some fundamentals of js, this example will look really familiar. You'd already know that writing the following code:
sayHello();
sayGoodbye();
will give errors (if you're lucky), or just unexpected results (if you aren't). This is because both functions rely on their scope for the this.name data, and calling them without explicit scope will just run them in the scope of the current window.
So how do we scope them? Try this:
sayHello.call(person1);
sayGoodbye.call(person2);

sayHello.apply(person1);
sayGoodbye.apply(person2);
All four of these lines do exactly the same thing. The run sayHello orsayGoodbye in the scope of eitherperson1 or person2.
Both call and apply perform very similar functions: they execute a function in the context, or scope, of the first argument that you pass to them. Also, they're both functions that can only be called on other functions. You're not going to able to runperson1.call(), nor does it make any sense to do so.
The difference is when you want toseed this call with a set of arguments. Say you want to make a say() method that's a little more dynamic:
var say = function(greeting){
    alert(greeting + ', ' + this.name);
};

say.call(person1, 'Hello');
say.call(person2, 'Goodbye');
So that's call for you. It runs the function in the context of the first argument, and subsequent arguments are passed in to the function to work with. So how does it work with more than one argument?
var update = function(name, age, size){
    this.name = name;
    this.age = age;
    this.size = size;
};

update.call(person1, 'Slarty', 200, '1xM');
No big deal. They're simply passed to the function if it takes more than one parameter.
The limitations of call quickly become apparent when you want to write code that doesn't (or shouldn't) know the number of arguments that the functions need… like a dispatcher.
var dispatch = function(person, method, args){
    method.apply(person, args);
};

dispatch(person1, say, ['Hello']);
dispatch(person2, update, ['Slarty', 200, '1xM']);
So that's where apply comes in - the second argument needs to be an array, which is unpacked into arguments that are passed to the called function.
So that's the difference between calland apply. Both can be called on functions, which they run in the context of the first argument. In call the subsequent arguments are passed in to the function as they are, while applyexpects the second argument to be an array that it unpacks as arguments for the called function.

Object Vs Prototype in JS

Its a pretty hard thing to wrap your mind around if you are used to the ease of extending objects in other OOP languages, but i'll do my best to explain the uses of those and what is what. I am going to assume you are familiar with other OOP languages. Correct me if i'm wrong.
All functions have the prototype Function(). They are inheriting all base functionlity from Function like toString() and valueOf().
Then there is a constructor. That is what you use to initialise an object with.
p = new Foo();
So in this case we have two things.
  • function Foo with Function as prototype(Foo)
  • Function object with Foo() as constructor(p)
(following me yet?)
The Foo() constructor can override some base functionality of theFunction constructor, but also leave it as it is and make good use of it.
If you are familiar with OOP priciples, The prototype is the base class, the constructor your current class. in OOP the above would be class Foo extends Function
You can also start inheritance with this entire setup of prototype and constructor making more complex objects as you go whilst sharing functionality.
For example this:
// make a object initialiser extending Function. in oop `class Foo extends Function`

function Foo(bar) {
    this.baz = bar;
}
Foo.prototype.append = function(what) {
    this.baz += " " + what;
};
Foo.prototype.get() {
    return this.baz
}
Now lets say we want different ways to get baz out of there. one for console logging and one for putting it on the title bar. We could make a big thign about our class Foo, but we dont do that, because we need to do wholly different things with the new classes but are made for different implementations. The only thing they need to share are the baz item and the setters and getters.
So we need to extend it to use an OOP term. in OOp this would be the desired end result class Title extends Foo(){}. So lets take a look how to get there.
function Title(what) {
    this.messsage = what;
}
At this point the Title function looks like this:
  • prototype Function
  • constructor Title
So, to make it extends Foo we need to change the prototype.
Title.prototype = new Foo();
  • prototype Foo
  • constructor Foo
This is done by initialising a new Foo() object against the prototype. Now its basically a Foo object called Title. That is not what we want because now we cant access the message part in Title. We can make it properly extend Foo() by resetting the constructor to Title
Title.prototype.constructor = Title;
  • prototype Foo
  • Constructor Title
Now we are faced with one more problem. The constructor of Foo doesnt get initialised so we end up with an undefined this.baz
To resolve that we need to call the parent. In java you would do that with super(vars), in php$parent->__construct($vars).
In javascript we have to modify the Title class constructor to call the constructor of the parent object.
So the Title class constructor would become
function Title(what) {
    Foo.call(this,what);
    this.messsage = what;
}
By using the Function object property Foo inherited we can initialise the Foo object in the Title object.
And now you have a properly inherited object.
So instead of using a keyword likeextend like other OOP languages it uses prototype and constructor.