Basics and more...
parseInt('06'); //6 parseInt('08'); //0
typeof NaN === 'number' //true NaN === NaN //false
0.1 + 0.2 === 0.3 // false
3.toString();
parseFloat( 'Infinity' ) // returns Infinity Number( 'Infinity' ) // returns Infinity parseInt( 'Infinity' ) // returns NaN
Number(true); // 1 Number(false); // 0
Boolean(null); // false null == false; // false
typeof null // "object" null instanceof Object // false
undefined = "a"; // possible
var foo = {}; foo.someMethod = function(){alert(this);}
As a function
var foo = function(){alert(this);} foo();
As a constructor
function Foo(){ this.confusing = 'hell yeah'; } var myObject = new Foo();
With Apply or Call methods
function foo(a,b){alert(this);} foo.apply('omg',['ah','be']);
function makeFunc(name) { return function() { alert(name); } } var myFunc1 = makeFunc("Aconex"); myFunc1(); var myFunc2 = makeFunc("SWAT"); myFunc2();
var newObject = {}; var newObject = Object.create( null ); var newObject = new Object();
Dynamically adding properties
newObject.key = "value"; newObject["key"] = "value";
Constructors: http://jsfiddle.net/c4dBW/
Constructors with prototypes
var mySingleton = (function () { var instance; function init() { var privateRandomNumber = Math.random(); return { getRandomNumber: function() { return privateRandomNumber; } }; }; return { getInstance: function () { if ( !instance ) { instance = init(); } return instance; } }; })(); // Usage: var singleA = mySingleton.getInstance(); var singleB = mySingleton.getInstance(); console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true
var a = 1 b = 1; (function(){ var a = 2 b = 2; }()) console.log(a); console.log(b);
function func() { return { foo: "bar" }; } func();
var1 == var2 var1 === var2
"1" == true "b" == true
'true' == true !!'true'
function func() { var a = "String"; function test(){ alert(a); var a = "Another String"; } test(); } func();
function func() { var a = "String"; function test(){ alert(a); function a(){alert("test")} } test(); } func();