Javascript function definition
//Define new function
var funcName = function (a) {
return a*a;
}
//Method invocation
var obj = {
name: 'objA',
ping: function() {
console.log('Ping from ' + this.name);
}
};
obj.ping();
//Function invocation
var obj = {
name: 'objA'
}
obj.ping = function() {
var that = this;
var helper = function () {
console.log('Ping from ' + that.name);
};
helper(); // Invoke helper as a function.
};
obj.ping();
//Constructor invocation
var Obj = function(name) {
this.name = name;
}
Obj.prototype.ping = function () {
console.log('Ping from ' + this.name);
};
var obj = new Obj('objA');
obj.ping();
//Apply invocation
var Obj = function(name) {
this.name = name;
}
Obj.prototype.ping = function () {
console.log('Ping from ' + this.name);
};
var obj = new Obj('objA');
Obj.prototype.ping.apply(obj);
//Function with variable argument list
var sum = function() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
// result is 6
var total1 = sum (1, 2, 3);
// result is 15
var total2 = sum (1, 2, 3, 4, 5);
//Throw/catch exception
var boom = function () {
throw {
name: 'KaboomError',
message: 'no reason'
};
console.log('never printed');
};
try {
boom();
}
catch (e) {
console.log('Exception happened: ' + e.name + '(' + e.message + ')');
}
//Function memoizer
var memoizer = function (memo, formula) {
var recur = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = formula(recur, n);
memo[n] = result;
}
return result;
};
return recur;
};
var fibonacci = memoizer([0, 1], function (recur, n) {
return recur(n - 1) + recur(n - 2);
});
//Closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var increment = makeAdder(1);
var add10 = makeAdder(10);
// 8
console.log(increment(7));
// 15
console.log(add10(5));