JavaScript language advanced tips and tricks
The guys behind the jslibs project have created a nice wiki with great JavaScript tips and tricks. Just see for yourself through the following samples. Some of them might not be available to all browsers but are worth a closer look…
Check if an object is not empty:
function isNotEmpty(obj) {
for ( var tmp in obj )
return true
}
Transform the arguments object into an array:
function foo() {
Array.slice(arguments); // is ['aa',11]
}
foo('aa',11);
The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system:
function MySingletonClass() {
if ( arguments.callee._singletonInstance )
return arguments.callee._singletonInstance;
arguments.callee._singletonInstance = this;
this.Foo = function() {
// ...
}
}
var a = new MySingletonClass()
var b = MySingletonClass()
Print( a === b ); // prints: true
Functions argument default value:
function foo( a, b ) {
a = a || '123';
b = b || 55;
Print( a + ',' + b );
}
foo(); // prints: 123,55
foo('bar'); // prints: bar,55
foo('x', 'y'); // prints x,y
Insert an array in another array:
var a = [1,2,3,4,5,6]
var b = ['a','b','c']
var insertIndex = 5;
Array.concat( a.splice( 0, insertIndex ), b, a );
// Result: 1,2,3,4,5,a,b,c,6