Consider this javascript object:
{ "name" : "Joe", "age" : "23"}
Javascript, being weakly typed, you can replace "23" (string) with 23 (number):
{ "name" : "Joe", "age" : 23}
Error, works fine.
Actually, you can replace 23 with something else: logical
{ "name" : "Joe", "age" : true}
another object
{ "name" : "Joe", "age" : {"2014" : 22 , "2015": 23 } }
or even a function
{ "name" : "Joe", "age" : function(){ alert("23");} }
Sidenote: Some people hate Javascript for being so weak. Other people (like me) love Javascript for the same reason, because this flexibility is its strength (it should be asynchronous).
You can call this object "person" and ask for its name and age:
var person = { "name" : "Joe", "age" : function(){ alert("23");} } console.log( person.name );
Now you can create a function that will return this object:
function Person() { return{ "name" : "Joe", "age" : function(){ alert("23");}, sayHello : function() { alert("Hello"); }, sleep : function() { alert("I'm sleeping"); } } }; console.log( Person().name );
age , sayHello and sleep are functions that are called methods of the Person function.
You can usually avoid calling Person() several times and instead create a new Person :
var person = new Person(); person.sayHello();
This method allows you to create many people by passing parameters:
function Person(name, age) { return{ "name" : name, "age" : function(){ alert(age);}, sayHello : function() {
This method currently replaces classes that lack Javascript 5 (EcmaScript 5). But EcmaScript 6 will be available soon with the appropriate classes.