Javascript training sample

Embed Size (px)

Citation preview

ADVANCE JAVA SCRIPT

TRAINING

JavaScript Basics

Very Popular Language.

Misunderstood programming language.

Dynamic Scripting Language.

Very few Language construct.

OOPs and Functional programming support **

Doesnt have Classes and Function are first class Objects. *This is an advantage not deficiency

Closure Support in Javascript for ages.

Very age old language

People assume it is similar to Java but it is not we will explain more in detail about this.

Var that compiled time checked variables.

So dynamic scripting.

Number ,String , Object, null,undefined, booleanNo int float double and other complex just 5 of them.

Functions are Objects they can be passed. So delayed operation and state change.

Passing function helps in creating DSL will talk later in depth.

Object oriented with out creating classes, there is some unlearning that is needed which we will provide in our slides below.

Annonymous Classes, JavaSwing are full of them but here in javascript programming it is back bone for good programming.

Reasons for Popularity

V8 Engine run out side browser

Node.js as server component

Out of box functional programming.

Very cool open source software available.

Popularity of Single screen applications.

Rhino jav8 support for java.

Mobile platforms based on basic javascript.

V8 scripting engine moved the javascript running environment out of browsers.

Node js is like apache seerver which can render server scripts with

Reflection in java can be run through for-in loop.

JavaScript Objects

Just 5 inbuilt objectsnull, undefined, String , number.

Very few in built objects ( But not a drawback)Array , Date , etc.

User defined objects can be defined.

User defined objects can be persisted as JSONvar variable_x = {}; // Basic Object.

Add attributes to a black object.

Gang of 4: perfect object composition 2 inheritance.

Console output

View in Chrome ctrl-shift-J

console.log(prahalad, Lord's Bhakt);

Takes variable argument

console.log(prahalad,1{},{lastName:das,firstName:prahalad});

This will print all of them in one line.

Console.dir( object ); this prints the whole object neatly in seperate lines.

Prototype Step 1

Inheritance in JS exists using Prototype.

Every Function you create has a prototype property.

This protype is an empty.

Convention OOPSFirst create class then create objects.

Protype is Copy Object.

Because of prototype there is less number of code.

Need more 2 discuss on this later slides.

eval is Evil

Dynamic Instantiation have helped LanguagesCreate framework.

Extend and call classes that you dont know.

THINK HOW TOMCAT instantiated your class without even knowing about the class.By Class.forName in java

But Eval does some thing similar.

But javascript scope defination creates pain.

Security concerns as the scope object could be compromised.

Bug free Vs Speed

Bugs are set back.Relook older code.

Revist the requirement.

Code changes have potential of breaking existing functionality of the application.

We will spend more time reading than writing.

So create code by patterns that are understood by the team.

Unit testing is essential, it also helps in reading code.

Minimize Global....how?

In Java code starts from main method.JS code starts the first line, as we keep including the js file it starts getting executed or recorded**

Because of first pt, the application starts generating global variables.

Weird gobal variable names by framework.$ - is the global variable created by jquery

_ - is the global variable created by underscore.js

So there are good posibility that we would be over writting the global variables.

Minimize global contd.

Global object accessed by this **outside function.

Global variables becomes attribute to top object. For JS in browser it is window_global_var = prahalad; //note var not used

console.log(window._global_var); console.log(this._global_var);//logic reused outside windows.Pattern use var to declare.

function sumNumbers(x, y) { result = x + y;//result is global can conflict, with third party or your own script. return result;//BIG PROBLEM}var a1 = a2 = 0;//a1 is local a2 is global; instead use var a1,a2;

Global contd..

Implied vs explicitly.

Declared with var outside function explicit global variable.

Delete Object Only applied to Implied object only not for explicit objects.

delete operator in javascript.delete a1;//deletes only implied objects not explicit objects.

JUST NOTE: Strict mode can throw exception

var global = (function () {return this;}());//*declare+execNow global can now be used in browser and phonegap or serverscripts application.

Global Contd..

Two slides before we discussed how JS is different from java(it starts from Main function)

Here is an example.

global_greet = "HELLO"; // global variablefunction func() { alert(global_greet); // "undefined" as in this scope global_var was in local scope var global_greet="Namaste";//NOTE :Scope is pushed forward at start of function alert(global_greet); // local scoped kicked in}Func( );//creates own scopeJavascript execution happens sequentially unlike Java.***

function func() { varglobal_greet // same as -> var global_greet = undefined; alert(global_greet); // "undefined" global_greet = "local"; alert(global_greet); // "local"}

//known as hoisting of variables, so it is a good practice to declare before than declaring any where when needed.

Basic Language Constructs

For Loop While loop remains same as other languages.

for-in - prefered to iterate on Object.

var house = {toilet: 2,bedRoom: 2,kitchen: 1,balcony=1,livingRoom=1,tvRoom=2};for(var room in house){ console.log( room );}We can add function and variable on fly in javascript.***

So assume we added will it show original object or the prototype object.

Interesting thing about JS vs Java & C++In java you cant change behaviour of object while it is running.

So transformer(movie) type CARS are never possible in java.Very much possible in JS.

Possible in java to some degree by SPRING or Dynamic-PROXY.

house.hasOwnProperty( room ) can check if it was manipulated.

Basic Language Constructs

Appending functionality across all objects.Refer & Explain Example basic_prototype_all_objects.html

Now you can append all the objects in the memory specific function.For example we want to add specific aspect or functionality across all Objects.

For example : Clone, persistance etc cross object functionality.

Inheritance in Java & C++In java & C++ world we create class human and then create instance.

Then common functionality of human becomes static variable.

Inheritance in javascript.It is a true copy of single object.

It is something like we all copied from Adam Or Eve.

This basic difference between how JAVA/C++/.net world differ from JS world.

Prototype can be dangerous

We have seen that it effects all objects.

Can potentially change all inbuilt object.

if (typeof Object.prototype.overideFunction!== "function") { //checking if we are overriding existing functionality Object.protoype.overideFunction = function () { // implementation... }; }Now the above change we have a potential that we dont know which all object have changed.

Change an Object at fly

Blacket change is bad how @ specific change.function employee(eName,title,dob){this.eName=eName;this.title=title;this.dob=dob;

}var nmurthy=new employee("N.Murthy","Mentor",1750);employee.prototype.salary=null;//no hoisting for this.nmurthy.salary=1;var prince =new employee("Rajkumar","CEO in Making",1973);console.dir(nmurthy);console.dir(price);

Ctnd...

Change objects at fly.

How we added salary variable to the employee class.

We can remove the salary function.

No hoisting happens for this, as scope happens.( price_ceo.html *** )

We can add function to an object.

Now when compared this to more statically typed language it is a great advantange.

Hoisting

Hoisting becomes complex

function firstFunction() {alert('global firstFunction');}; function secondFunction() {alert('global secondFunction2');}; function hoistingIssue() { console.log(typeof secondFunction); console.log(typeof firstFunction); secondFunction(); //firstFunction(); //will fail function secondFunction() {alert('local secondFunction');}//function hoisting var firstFunction = function () { alert('local firstFunction'); };//variable hoisting blank FirstFunction();//now it works, variable is posted with function type } hoistingIssue();//hoisting of local variable begins.

Implied Type Casting

false==0 -- true

XYZ==true -- true

false===0 --falseChecks data type.

Then compared value.

Not check reference.

Do you know you can return undefinedVery useful most of the language dont have this feature

function canReturnUndefined(){return undefined;// keyword }

Tools & Convention

Function called with new acts as constructor.

Class starts with first letter CAPITAL.

Private variable and private function starts with underscore.Note all these are not mandatory but a convension of this industry.

Jsdoc most used to create js documentation of the API.

Comment annotation used to create jsdoc.

Google closurer tool to mimify

Dynamic Language

Most of the dynamic languages supports simplified object constructor.They hold attribute and function as attributes of hashmap.

You can add attributes after the object is constructed.

var pet = {};// add one propertypet.name = "Pottu";// now add a methodpet.getName = function () {return pet.name;};We added attribute to my pet after it was created.delete dog.name;

JavaScript Literals

Above example literal object json

var pet = { name: "Pottu", //literal seperator is, getName: function () { return this.name; } };Above object can be passed to any other languages could also be converted to respective languages Object.

For example gson for java.

Few built-in constructor number(),Date(),String(),Object()

JSon

Literal presentation of object.

Persisted and passed around network and database (mangoDB/clob rows).

var data = JSON.parse(jstr);//objects get createdSo network application can pass object state in string format.

var jsonstr = JSON.stringify(dog);We can get string persistable state of an Object.

Similar to classes

Pay attention to RED color keyword in code.

var Person = function (name) { //implicit call var this={} this.name = name; this.say = function () {//why implicit this was not created here and effected this? return "I am " + this.name; }; //return this;//implicits };Note this outside a function scope refers to global object like window or phonegap objects.

JavaScript Constructor

A function can be called with or with out new

When called with new returns Object this.

When called without new it executes function.

This is very important concept to grab.CONSTRUCTOR.html***

When created with new it creates __proto__ attribute to understand if it was a function or an object from console.function human(name){//this={}; implicitthis.name = name;this.introduceHuman=function (){return "HI i am "+this.name;}}//return this;

var nonNewPrahalad = human("Prahalad"); var newPrahalad = new human("Prahalad");console.dir( newPrahalad );console.dir( nonNewPrahalad );//returns undefined.

human.prototype.sayBye = function () {return "Bye Bye" ;};//add attr&Function

Constructors and Convention

Constructor if not used with convention can be disaster, if not use properly you will spend days debugging it SO PLEASE PAY ATTENTION.

Project success has hundred fathers, for failed javascript project have a single father Developer who dont understand this slide ( JOKE ).Assume we have a global variable name in the above example.

name = "God";//global variable function Human(name){//check the function with capital letter(so Class) this.name = name;//change global variable this.introduceHuman=function (){ return "HI i am "+this.name;} } Human(prahalad);//this will change global variable.(note: new operator not used) console.log("Told u to use new operator, so god is now : "+ name);

Avoid Problem with that

function Human(name) { var that = {}; that.name = name; that.introduce= function(){ return Hey my name+that.name; } return that;}//GOOD PATTERN MUST FOLLOW THISThat helped me a lot as what ever i write i would not cpawanPutrahange the global variable.

So my code remains safe.

that is not a key word name convention

Force Function call 2 Constructor

We can force function call to constructor call.

instanceof operator does work to check if they used constructor.

function Human(name){ if ( !(this instanceof Human) ) { return new Human(); // trick is here }//another better way is = new arguments.callee( ) ** bit advance concept. this.name...//code not completed}var instance = Human(prahalad);

You always create object inspite of not using new operator. Good for API developers.

Call Backs!!

All major framework use this concept.You dont call me I will you, when time and scenario arrive.

Servlet Container call your Servlet in JAVA.

So how call back in java

function i_will_call_you_Back(registered_callback) { // can do something... registered_callback();//can check if it is a function before you fire it. // post call back operation like reply object handling }

Paid Training

Contact http://it-corporate-trainer.prahalad-das.in

Note this is a paid Training.

This slide is just to show case our depth of understanding in this subject.

It is a complete 3 days training.

Training includes training handout(hardcopy), worksheet & practice examples also.