daemonl_

In case you were wondering...

JS104 - functions and new

This is part of a series. You may like to read the other parts first.

It will help to remember that functions are objects. and they can be declared a few different ways, these are the two non weird ways, and they both do exactly the same thing:

function a {  
  alert("boo");  
}   
var a = function {  
  alert("boo");  
}   

Here's some normal, every day javascript:

var a = {};  
  a.prop = "Property";  
  console.log(a.prop); // "Property"  

Now let's wrap it in a function:

var c = function()  
{  
  var a = {};  
  a.prop = "Property";  
  return a;  
}  

var b = c();  
console.log(c.prop);  

It still does the same thing. Just moved around a bit. So let's add the 'new' keyword. keep in mind that we are still doing exactly the same thing:

var c = function()  
{  
  this.prop = "Property";  
}  

var b = new c();  
console.log(c.prop);  

We didn't have to define 'a' any more, instead we used the already existing 'this', all because the function was called using 'new'

The 'new' keyword does a few things:

  1. Firstly, it creates a new object {}
  2. Then it populates that object's keys with the keys of 'this' in the function,
  3. Then it assigns the 'prototype' in the function to the newly created object's proto
  4. And finally it assigns the new object's property 'constructor' to the function used to create it ('c' in this case)

Notice that 'this' doesn't need to be declared like var this = {}... in fact, totally don't do that, it's 'pre created' for you by using 'new'

var c = function()  
{  
  this.prop = "property";  
}  
c.prototype.getProp = function(){ return this.prop; };  

var b = new c();  
console.log(b.getProp());  

  // And then:  

console.log(b.constructor);  
  // Which means:  
b.constructor.prototype.n = "aNother Property";  

console.log(b.n); // "aNother Property"  

What we did there was assign a new value, a function, to the 'prototype' key of 'c'

'c' is a function, but - this is javascript - c is an object, a set of keys and values, one of those is it's proto which gets the 'Function' in built functionality. It also has the actual code which the function does when it is called. I don't know what key, if any, that is stored in, but you can see it by console.log'ing the function without (). ( 'console.log(c)' )

One of the important keys for the function is it's 'prototype', which can be set as above, and is used as the proto of any new object created with putting 'new' before calling that function.

Now why do we do this? Firstly it helps organise code - it's nicer to have things organised into objects, but that's not the half of it, and doesn't really explain 'new'. Javascript is fully capable of object oriented programmi.... ok, that hurt a little bit... it's not fully capable, but it has quite a lot... some... a few of the things object oriented programming has. But that's a post for another day.