BY Mohammed Alsaffar m.9afar@gmail @9afar on Twitter
In JavaScript everything is an object except for null and undefined
false.toString(); // 'false' [1, 2, 3].toString(); // '1,2,3' function Foo(){} Foo.bar = 1; Foo.bar; // 1
Using an object literal - {} notation - it is possible to create a plain object. This new object inherits from Object.prototype
var foo = {}; // a new empty object // a new object with a 'test' property with value 12 var bar = {test: 12};
The properties of an object can be accessed in two ways, via either the dot notation or the square bracket notation.
var foo = {msg: 'hello'} foo.msg; // hello foo['msg']; // hello var VarName = 'msg'; foo[VarName]; // hello foo.1234; // SyntaxError foo['1234']; // works
var test = { myKey: 'I am a key', 'case': 'I am a keyword, so I must be notated as a string', delete: 'I am a keyword, so me too' // raises SyntaxError }; test.myKey; // I am a key test.case; // I am a keyword, so I must be notated as a string
foo(); // Works because foo was created before this code runs function foo() {}
The above function gets hoisted before the execution of the program starts; thus, it is available everywhere in the scope it was defined, even if called before the actual definition in the source.
var foo = function() {};
This example assigns the unnamed and anonymous function to the variable foo.
foo; // 'undefined' foo(); // this raises a TypeError var foo = function() {};
since assignments only happen at runtime, the value of foo will default to undefined before the corresponding code is executed.
$(function(){ // on load code here });
This is an example of an anonymous function
function divide(n1 , n2 , onSuccess , onError){ try{ if (n2 == 0) throw "Can not divide by zero"; var result = n1 / n2; onSuccess(result); }catch(err){ console.log(err); onError(err); } } divide( 1 , 2 , function(result){ $('#divideValue').css('background','green'); $('#divideValue').text(result); } , function(errorMsg){ $('#divideValue').css('background','red'); $('#divideValue').text(errorMsg); } );
(function(){ // function calling it self alert("Hi, I just called my self!!"); })();
(// evaluate the function inside the parentheses function(){ // function calling it self alert("Hi, I just called my self!!"); } // and return the function object ) ();// call the result of the evaluation
var apple = { type: "macintosh", color: "red", getInfo: function () { return this.color + ' ' + this.type + ' apple'; } }
In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
apple.color = "reddish"; alert(apple.getInfo());
This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function() you use the this keyword, as seen in the following example.
function Apple (type) { this.type = type; this.color = "red"; // anti-pattern! ( this is wrong ) keep reading... this.getInfo = getAppleInfo; } function getAppleInfo() { return this.color + ' ' + this.type + ' apple'; } var apple = new Apple('Red'); apple.color = "#ff0000"; alert(apple.getInfo());
JavaScript does not feature a classical inheritance model; instead, it uses a prototypal one.
Class methods should be defined inside the class prototype
function Apple (type) { this.type = type; this.color = "red"; } // Instance method will be available to all instances but only load once in memory Apple.prototype.getInfo = function() { return this.color + ' ' + this.type + ' apple'; };
function Greeter(message) { this.greeting = message; Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; } var greeter = new Greeter("GCE"); $("#GreeterMsg").text(greeter.greet());
var Greeter = (function(){ function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })(); var greeter = new Greeter("GCE"); $("#GreeterMsg2").text(greeter.greet());
$("#ThisGSResult").text(this.constructor.name);
function Test(){ $("#ThisFResult").text(this.constructor.name); } Test();
function Test(){ $("#ThisCResult").text(this.constructor.name); } new Test();
var MyClass = (function(){ function MyClass() {} MyClass.prototype.Test = function () { $("#ThisICResult").text(this.constructor.name); }; return MyClass; })(); var myClass = new MyClass(); myClass.Test();
var MyClass = (function(){ function MyClass() { $("#clickme").click(this.msg); //$("#clickme").click(this.msg.bind(this)); } MyClass.prototype.msg = function () { $("#clickme").text("Hello from " + this.constructor.name); }; return MyClass; })(); var myClass = new MyClass();
var Counter = (function(){ Counter.Current = 0; // Static Variable function Counter() { this.Current = 0; // Public Variable } Counter.prototype.Count = function () { Counter.Current++; this.Current++; }; return Counter; })(); var counter1 = new Counter(); var counter2 = new Counter(); counter1.Count(); counter1.Count(); counter2.Count(); $("#CounterResult").text(Counter.Current);
Inheritance in javascript is done by adding to the prototype chain and copying property definitions Using this function
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); };
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Animal = (function () { function Animal(name) { this.name = name; } Animal.prototype.move = function (meters) { alert(this.name + " the " + this.constructor.name +" moved " + meters); }; return Animal; })(); var Snake = (function () { var _super = Animal; __extends(Snake, _super); function Snake(name) { _super.call(this, name); } Snake.prototype.move = function () { _super.prototype.move.call(this, 5); }; return Snake; })(); var Horse = (function () { var _super = Animal; __extends(Horse, _super); function Horse(name) { _super.call(this, name); } Horse.prototype.move = function () { _super.prototype.move.call(this, 45); }; return Horse; })(); function TestAnimals(){ var sam = new Snake("Sam"); var tom = new Horse("Tom"); sam.move(); tom.move(); }