Clojures in JS

var createObject = function (value) {
    return {
        increment: function (inc) {
            value += inc;
        },
        getValue: function () {
            return value;
        }
    }
};
 
 
//The methods of the created object can
//continue to access the "value" variable
//after the createObject() function ends
var myObject = createObject(2);
console.log(myObject.getValue());
myObject.increment(2);
console.log(myObject.getValue());

Invocation Patterns in JS

The JS Invocation Patterns are the ways we can invoke a function and the differences (for example on the “this” variable binding) between them.

//--------------------------
//Method Invocation Pattern
//--------------------------

var myObject = {
    value: 0,
    increment: function (inc) {
        console.log(this);
        this.value += inc;
    }
}

//Since I'm invocating the increment()
//function as a method (<object>.<method>)
//"this" is bound to the object

myObject.increment(2);
console.log(myObject.value);

//-----------------------------
// Function Invocation Pattern
//-----------------------------

var sum = function (a, b) {
    console.log(this);
    return a + b;
}

//Since I'm invoking the sum() function
//as a function "this" is bound to the
//global object (window)

var sumRes = sum(2, 3);
console.log(sumRes);

//--------------------------------
// Constructor Invocation Pattern
//--------------------------------

var MyClass = function (status) {
    console.log(this);
    this.status = status;
}

//Since I'm invoking the MyClass() function
//as a constructor (new <constructor>)
//"this" is bound to the new object

var myClassObject = new MyClass("happy");
console.log(myClassObject.status);

//-------------------------------
// Apply/Call Invocation Patterns
//--------------------------------

var sub = function (a, b) {
    console.log(this);
    return a - b;
}

//Since I'm invoking the sub() function
//with Apply/Call "this" is bound to the
//object passed as first parameter

//Apply() accept the function's arguments
//as an array

var subResWithApply = sub.apply({ name: "this1" }, [5, 3]);
console.log(subResWithApply);

//Call() accept the function's arguments
//as a comma separated list

var subResWithCall = sub.call({ name: "this2" }, 5, 3);
console.log(subResWithCall);

And here is the output: