Introduction To Javascript

37
A Quick Intro to Javascript Rajat Pandit ([email protected] ) 1 Thursday, September 24, 2009

description

 

Transcript of Introduction To Javascript

Page 1: Introduction To Javascript

A Quick Intro to Javascript

Rajat Pandit ([email protected])

1Thursday, September 24, 2009

Page 2: Introduction To Javascript

Data TypesObjectFunctionNumbersStringsBooleansnull - a value that isn’t anythingundefined - default value for variables and parameters, value of missing members in the object etc

2Thursday, September 24, 2009

Page 3: Introduction To Javascript

ObjectsObjects can contain data and methodsObjects can inherit from other objectsAn object contain an unordered collection of name/value pairsValues can be any type including other objectsJSON

3Thursday, September 24, 2009

Page 4: Introduction To Javascript

Object LiteralsObjects 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

4Thursday, September 24, 2009

Page 5: Introduction To Javascript

Creating a new Objectnew Object(){ } - Preferred formatBoth are the sameObjects are passed by reference not by value=== operator compares references, not values, true only if the operands are the same objectMembers can be removed using the delete operator

delete myobject[name];

5Thursday, September 24, 2009

Page 6: Introduction To Javascript

Object Examplevar myobject = { name : “Jack Appleseed”, “data”: { foo: 10, bar: 20}};var data = myobject.data;var foo = myobject.data.foo;

6Thursday, September 24, 2009

Page 7: Introduction To Javascript

Object AugmentationNew members can be added to any objectNo need to define a new class

myobject.format.colormodel = ‘foo’;myobject[another_new_member] = 34;

7Thursday, September 24, 2009

Page 8: Introduction To Javascript

Object Augmentation

More on prototype in the next few slidesPrototype library does the sameVery messy approach, pollutes the expected behavior

String.prototype.trim = function() { return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");

}

8Thursday, September 24, 2009

Page 9: Introduction To Javascript

typeof Prefix OperatorThe typeof prefix operator returns a string identifying the type of valueUse instanceof instead Type typeof

object ‘object’function ‘function’array ‘object’number ‘number’string ‘string’boolean ‘boolean’null ‘object’undefined ‘undefined’

9Thursday, September 24, 2009

Page 10: Introduction To Javascript

ArrayArray inherits from Object (like every other object in JavaScript)No need to provide length when creating a new oneUnlike object they have a length member and is always 1 larger than the highest subscriptDo not use for ... in for arraysAppending new itemmylist[mylist.length] = ‘foo’

10Thursday, September 24, 2009

Page 11: Introduction To Javascript

Arrayvar my_array = ['abc', 'xyz', 'foo'];var my_object = {foo: 10, bar:20, baz:200}

for (x in my_array) { console.log(x + ‘-’ + my_array[x]);}

Array.prototype.this_is_super_lame = 'fooo';

Output:0 - abc1 - xyz2 - foo

Output:0 - abc1 - xyz2 - foothis_is_super_lame - fooo

11Thursday, September 24, 2009

Page 12: Introduction To Javascript

Array Methodsconcatjoin (can also be used for concatenating multiple strings)poppushslicesortsplice

Use Objects when you think you need associative array (PHP Developers) you are should be using Object not Array.

12Thursday, September 24, 2009

Page 13: Introduction To Javascript

Checking for Array

value.constructor === Array

value instanceof Array

13Thursday, September 24, 2009

Page 14: Introduction To Javascript

FunctionThey are first class ObjectsCan be passed, stored and returned just like any valueInherit from object and store name/value pairsFunction can appear anywhere an expression can appear

14Thursday, September 24, 2009

Page 15: Introduction To Javascript

Function Cont...Functions can be contained inside other functionsInner function has access to the variable and parameters of the function it is contained withinThis is static or lexical scopingThe scope that inner function has access to continues even after the parent function has returned. This is called Closure

15Thursday, September 24, 2009

Page 16: Introduction To Javascript

Function Cont...Function inside an object is called a methodWhen invoked with too many arguments, the rest are ignoredWhen invoked with fewer arguments, the rest are set to undefinedNo type checking

16Thursday, September 24, 2009

Page 17: Introduction To Javascript

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();

Output10

17Thursday, September 24, 2009

Page 18: Introduction To Javascript

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();

Output5

18Thursday, September 24, 2009

Page 19: Introduction To Javascript

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();

19Thursday, September 24, 2009

Page 20: Introduction To Javascript

Function (arguments)When function is invoked, in addition to its parameters it has a special parameter called argumentsContains all arguments from invocationarguments.length will tell you how many arguments were passedarguments is not of type Array even though it has length

20Thursday, September 24, 2009

Page 21: Introduction To Javascript

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 :objectobjecttruefalse

21Thursday, September 24, 2009

Page 22: Introduction To Javascript

As crockford says, the object that dare not speak of its nameIt 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

(global) Object

22Thursday, September 24, 2009

Page 23: Introduction To Javascript

GLOBAL VARIABLES ARE EVILUn-namespaced values can clobber each others valuesUse of it should be minimized or gotten rid of totallyVariables defined in the function / module should start with var otherwise they have a global scope

23Thursday, September 24, 2009

Page 24: Introduction To Javascript

Inheritance

OOP ensures code reuseTwo forms of OOP- Classical - Prototypal

24Thursday, September 24, 2009

Page 25: Introduction To Javascript

prototypeJavaScript functions work as methods, constructors and modulesIt has Prototypal Inheritance, instead of classical inheritance

This offers great expressive powersAll objects are directly or indirectly linked to Object.prototype

25Thursday, September 24, 2009

Page 26: Introduction To Javascript

prototypeEach object is linked to its parent via a magic linkWhen a member is accessed the compiler looks at the object and then looks up to its parent via the magic linkIt keeps going all the way up to Object.prototype

26Thursday, September 24, 2009

Page 27: Introduction To Javascript

prototypemy_object = { foo: 10, bar:15

my_object_parent = { bar: 10,

Object

prototype prototype

Looking for my_object.foo, found it in the object itselfLooking 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

27Thursday, September 24, 2009

Page 28: Introduction To Javascript

prototypeAugmenting 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

28Thursday, September 24, 2009

Page 29: Introduction To Javascript

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();

29Thursday, September 24, 2009

Page 30: Introduction To Javascript

Prototypal Inheritancevar BiggerConstructor = function() {};BiggerConstructor.prototype = new Test();var a = new BiggerConstructor();a.new_function();

function object(o) { function F() {}; F.prototype = o; return new F ();}

Another way of doing Inheritance

30Thursday, September 24, 2009

Page 31: Introduction To Javascript

SingletonThere is no need to produce a class-like constructor for an object that will have exactly one instanceThis is typical of JavaScript applicationsUse an object literal to get started instead

31Thursday, September 24, 2009

Page 32: Introduction To Javascript

SingletonYou 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) { }}

32Thursday, September 24, 2009

Page 33: Introduction To Javascript

Module PatternThe methods of a singleton can enjoy access to shared private datum and private methodsVariables defined in a module are only visible in a moduleVariables defined in a function are only visible to the functionFunction can be used as module containers

33Thursday, September 24, 2009

Page 34: Introduction To Javascript

Module Patternvar my_module = function() { var privateVariable, privateFunction = function() { // stuff }; return { firstMethod: function(a,b) { // can access privateVariable // can access privateFunction } }}();

my_module.firstMethod();

34Thursday, September 24, 2009

Page 35: Introduction To Javascript

Privileged MethodsMethods in the return object are called Privileged methodsThey have access to the secret information

Has access to private variables and methods

Obtains its secret information through closure

35Thursday, September 24, 2009

Page 36: Introduction To Javascript

Power Constructor

Many Patterns here

private variables (var)private methods (inner functions)privileged methods (that.firstmethod)

no more need for use of newmy_object = PowerConstructor();

function PowerConstructor() { var that = {}, privateVariable = 40; that.firstMethod = function(a,b) {// private access} that.secondMethod = function(c) {// private access} return that;}

36Thursday, September 24, 2009

Page 37: Introduction To Javascript

ResourcesCoding conventionhttp://javascript.crockford.com/code.htmlLinting JavaScripthttp://jslint.orgMozilla Developer Center for JavaScripthttps://developer.mozilla.org/en/JavaScript

37Thursday, September 24, 2009