1. A Quick Intro to
Javascript
Rajat Pandit (rajat_pandit@ipcmedia.com)
Thursday, September 24, 2009 1
2. Data Types
Object
Function
Numbers
Strings
Booleans
null - a value that isn’t anything
undefined - default value for variables
and parameters, value of missing members
in the object etc
Thursday, September 24, 2009 2
3. Objects
Objects can contain data and methods
Objects can inherit from other objects
An object contain an unordered
collection of name/value pairs
Values can be any type including other
objects
JSON
Thursday, September 24, 2009 3
4. Object Literals
Objects are wrapped in { }
Names can be string
Value can be an expression
; used for separation
, separate pairs
Object literals can be used
anywhere a value can appear
Thursday, September 24, 2009 4
5. Creating a new Object
new Object()
{ } - Preferred format
Both are the same
Objects are passed by reference not by value
=== operator compares references, not values,
true only if the operands are the same object
Members can be removed using the delete
operator
delete myobject[name];
Thursday, September 24, 2009 5
6. Object Example
var myobject = {
name : “Jack Appleseed”,
“data”: { foo: 10, bar: 20}
};
var data = myobject.data;
var foo = myobject.data.foo;
Thursday, September 24, 2009 6
7. Object Augmentation
New members can be added to
any object
No need to define a new class
myobject.format.colormodel = ‘foo’;
myobject[another_new_member] = 34;
Thursday, September 24, 2009 7
8. Object Augmentation
String.prototype.trim = function() {
return this.replace(/^s*(S*(s+S+)*)s*$/,
"$1");
}
More on prototype in the next few
slides
Prototype library does the same
Very messy approach, pollutes the
expected behavior
Thursday, September 24, 2009 8
9. typeof Prefix Operator
The typeof prefix operator returns a
string identifying the type of value
Use instanceof instead Type typeof
object ‘object’
function ‘function’
array ‘object’
number ‘number’
string ‘string’
boolean ‘boolean’
null ‘object’
undefined ‘undefined’
Thursday, September 24, 2009 9
10. Array
Array inherits from Object (like every other
object in JavaScript)
No need to provide length when creating a new
one
Unlike object they have a length member and
is always 1 larger than the highest subscript
Do not use for ... in for arrays
Appending new item
mylist[mylist.length] = ‘foo’
Thursday, September 24, 2009 10
12. Array Methods
concat
join (can also be used for concatenating multiple strings)
pop
push
slice
sort
splice
Use Objects when you think you need associative array (PHP
Developers) you are should be using Object not Array.
Thursday, September 24, 2009 12
13. Checking for Array
value.constructor === Array
value instanceof Array
Thursday, September 24, 2009 13
14. Function
They are first class Objects
Can be passed, stored and
returned just like any value
Inherit from object and store
name/value pairs
Function can appear anywhere
an expression can appear
Thursday, September 24, 2009 14
15. Function Cont...
Functions can be contained inside other
functions
Inner function has access to the variable
and parameters of the function it is
contained within
This is static or lexical scoping
The scope that inner function has access
to continues even after the parent
function has returned. This is called
Closure
Thursday, September 24, 2009 15
16. Function Cont...
Function inside an object is
called a method
When invoked with too many
arguments, the rest are ignored
When invoked with fewer arguments,
the rest are set to undefined
No type checking
Thursday, September 24, 2009 16
17. Function Cont...
When a function is invoked in method
format, this refers to the object
containing it.
var foo = {
baz: 10,
bar: function() {
console.log(this.baz); // cant access baz
// directly
}
};
foo.bar();
Output
10
Thursday, September 24, 2009 17
18. Function Cont...
When object is invoked in function,
this refers to the global object
var global_variable = 5;
function test() {
console.log(this.global_variable);
}
test();
Output
5
Thursday, September 24, 2009 18
19. Function Cont...
When new Function is used (implicit return is
optional), then this returns the new object
created
var Test = function(id) {
this.something = id;
this.foo = function() {
console.log('this is a test: ' + this.something);
}
}
var o = new Test(10),
i = new Test(111);
o.foo();
i.foo();
Thursday, September 24, 2009 19
20. Function (arguments)
When function is invoked, in addition
to its parameters it has a special
parameter called arguments
Contains all arguments from invocation
arguments.length will tell you how
many arguments were passed
arguments is not of type Array even
though it has length
Thursday, September 24, 2009 20
21. Function (arguments)
Code:
var foo = function() {
var a = new Array();
console.log( typeof a );
console.log( typeof arguments );
console.log( arguments instanceof Object );
console.log( arguments instanceof Array );
}
foo();
Output :
object
object
true
false
Thursday, September 24, 2009 21
22. (global) Object
As crockford says, the object that
dare not speak of its name
It is the container for all global
variables and all built in objects
On browsers window is the global
object
Variables defined with a var makes
it local to the scope
Thursday, September 24, 2009 22
23. GLOBAL VARIABLES ARE EVIL
Un-namespaced values can clobber
each others values
Use of it should be minimized or
gotten rid of totally
Variables defined in the
function / module should start
with var otherwise they have a
global scope
Thursday, September 24, 2009 23
24. Inheritance
OOP ensures code reuse
Two forms of OOP
- Classical
- Prototypal
Thursday, September 24, 2009 24
25. prototype
JavaScript functions work as
methods, constructors and modules
It has Prototypal Inheritance,
instead of classical inheritance
This offers great expressive powers
All objects are directly or
indirectly linked to
Object.prototype
Thursday, September 24, 2009 25
26. prototype
Each object is linked to its
parent via a magic link
When a member is accessed the
compiler looks at the object and
then looks up to its parent via
the magic link
It keeps going all the way up
to Object.prototype
Thursday, September 24, 2009 26
27. prototype
my_object = { my_object_parent
foo: 10, = { Object
bar:15 bar: 10,
prototype prototype
Looking for my_object.foo, found it in the object itself
Looking for my_object.baz looks in the object and if it
doesn’t find it there it goes to my_object_parent which
is my_object.prototype
Looking for my_object.some_random_member can’t find it
in the object, look at my_object_parent, can’t find it
there either, goes to Object can’t find it there and is
set to undefined
Thursday, September 24, 2009 27
28. prototype
Augmenting the ancestor will have an
affect on all the children, even the
ones that were created before the
augmentation
Augmentation can be done via the
prototype property that each object
has
Thursday, September 24, 2009 28
29. prototype
var Test = function(id) {
this.something = id;
this.foo = function() {
console.log('this is a test: ' + this.something);
}
// implicit return not required
}
var o = new Test(10),
i = new Test(111);
o.foo();
i.foo();
Test.prototype.new_function = function() {
console.log('i am a new function');
}
o.new_function();
Thursday, September 24, 2009 29
30. Prototypal Inheritance
var BiggerConstructor = function() {};
BiggerConstructor.prototype = new Test();
var a = new BiggerConstructor();
a.new_function();
Another way of doing Inheritance
function object(o) {
function F() {};
F.prototype = o;
return new F ();
}
Thursday, September 24, 2009 30
31. Singleton
There is no need to produce a
class-like constructor for an
object that will have exactly
one instance
This is typical of JavaScript
applications
Use an object literal to get
started instead
Thursday, September 24, 2009 31
32. Singleton
You have seen it before
The methods of a singleton can enjoy
access to shared private data and
private methods
var singleton = {
firstFunction: function(a,b) {
},
secondFunction: function(c) {
}
}
Thursday, September 24, 2009 32
33. Module Pattern
The methods of a singleton can enjoy
access to shared private datum and
private methods
Variables defined in a module are only
visible in a module
Variables defined in a function are
only visible to the function
Function can be used as module
containers
Thursday, September 24, 2009 33
34. Module Pattern
var my_module = function() {
var privateVariable,
privateFunction = function() {
// stuff
};
return {
firstMethod: function(a,b) {
// can access privateVariable
// can access privateFunction
}
}
}();
my_module.firstMethod();
Thursday, September 24, 2009 34
35. Privileged Methods
Methods in the return object are
called Privileged methods
They have access to the secret
information
Has access to private variables and
methods
Obtains its secret information
through closure
Thursday, September 24, 2009 35
36. Power Constructor
function PowerConstructor() {
var that = {},
privateVariable = 40;
that.firstMethod = function(a,b) {// private access}
that.secondMethod = function(c) {// private access}
return that;
}
Many Patterns here
private variables (var)
private methods (inner functions)
privileged methods (that.firstmethod)
no more need for use of new
my_object = PowerConstructor();
Thursday, September 24, 2009 36
37. Resources
Coding convention
http://javascript.crockford.com/
code.html
Linting JavaScript
http://jslint.org
Mozilla Developer Center for
JavaScript
https://developer.mozilla.org/en/
JavaScript
Thursday, September 24, 2009 37