Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, December 16, 2015

Don't be Surprise If your website breaks in IE9 ! Console.log

Don't be surprise if something start breaking up in IE9 after you go for big bang release and customer started complaining website is not working. The reason is pretty straight forward, javascript and client scripting is taking centre stage and all new browsers support them very much. Console.log is common script that most of the developer used to trace the flow of javascript. It happens they forgot to uncomment them while release to production. It is rare case when big enterprise application fails to ensure this is taken care.


http://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function


Monday, January 6, 2014

Variable Scoping in Javascript

It is always important to make use of VAR to declare variable identifiers. If you miss doing this , there are two implications.

1. It is then by default act as GLOBAL variable.

2. Chances are these variables will be overwritten everytime developers uses same variable name across the modules. This is worst defect and sometimes difficult to figure it out.

/* Declared globally. */

function FindTruth(id) {


}


// Later in your page, another programmer adds…

var FindTruth= $(‘Overwritten-False-Fact’); // The FindTruth function just got

// overwritten.

Namespacing- Best Practice



/* Using a namespace. */

var MyNamespace = {

FindTruth: function(id) {


},

// Other methods can go here as well.

}

// Later in your page, another programmer adds…
var Findtruth= $(‘Overwritten-False-Fact’);// Nothing was overwritten.

In JavaScript Object Oriented programming this is Singleton pattern.

Now one can access method using MyNamespace.Findtruth(Id);

We can even structure it separately and then later add group of methods to decorate as library.

/* Super namespace. */

var SuperLib = {};

SuperLib.Common = {

// A singleton with common methods used by all objects and modules.

};

SuperLib.DataAccess= {

//Hold and transfer data

};

SuperLib.Helper= {

//Html Helper

};

!! Negation in Javascript

Double negation casts a string or a number to a boolean:
var bool = !!num;
The following values are equivalent to false in conditional statements:
  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN
All other values are equivalent to true.
var x = "somevalue" var isNotEmpty = !!x.length;
Let’s break it to pieces:
x.length   // 9
!x.length  // false
!!x.length // true
 

Some Useful Basic Different ways of Javascript Coding

Style 1 Procedural Way

/* Start and stop animations using functions. */

function startAnimation() {


}

function stopAnimation() {


}

Style 2: using Prototype to define Class function

/* Anim class. */

var Anim = function() {


};

Anim.prototype.start = function() {


};

Anim.prototype.stop = function() {


};

/* Usage. */

var myAnim = new Anim();

myAnim.start();

myAnim.stop();

Style 3: Encapsulated Prototyping

/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() {


};

Anim.prototype = {

                start: function() {

               …

              },

               stop: function() {

              …

 }

};

Style 4: Function.prototype.method

/* Add a method to the Function object that can be used to declare methods. */

Function.prototype.method = function(name, fn) {

                this.prototype[name] = fn;

};

/* Anim class, with methods created using a convenience method. */

var Anim = function() {


};

Anim.method(‘start’, function() {


});

Anim.method(‘stop’, function() {


});



Style 5: Chain Function Approach

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {

                     this.prototype[name] = fn;

                    return this;

};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() {


};

Anim.method(‘start’, function() {


})

.method(‘stop’, function() {


});

Tuesday, December 3, 2013

Javascript Identity Operator vs Equality Operator

 

Equality and inequality tests

==, !=
It checks and compare values of the variable.
 

Example

var firstVal = 5;//Number

var secondVal = "5";//String

if (firstVal == secondVal) {

console.log("They are the equal");

} else {

console.log("They are NOT the equal");

}

Output:They are the equal
 ONlY Values are compared.

 

Identity and nonidentity tests

===, !== It checks and compare values and types of the variable.

Example

var firstVal = 5; //Number

var secondVal = "5"; //String

if (firstVal === secondVal) {

console.log("They are the same");

} else {

console.log("They are NOT the same");

}

Output : They are  NOT the same.

Values and Types are compared.
 

Thursday, August 22, 2013

__defineSetter__ and .__defineGetter in javascript

The definesetter and definegetter reminds of how we used look into MSIL code using disassembler tool. On Similar line in javascript the line interpreter does this.


 if (Object.prototype.__defineGetter__)
    return obj.__defineGetter__(prop, get);

 if (Object.prototype.__defineSetter__)
    return obj.__defineSetter__(prop, set);


Courtesy By






http://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/

As you may have noticed, all examples here use Object.defineProperty in preference to either __defineGetter__ or __defineSetter__, using the latter two only as fallback when the former is absent. While many browsers support these methods, not all do. Object.defineProperty is the future, and it is the standard; Microsoft has even gone on the record to say that they will not implement __defineGetter__ or __defineSetter__ in IE given the existence of the standardized method (props to them for that choice, by the way). For greatest forward compatibility with all browsers, you should use Object.defineProperty if it exists, and only fall back to __define{G,S}etter__ if it does not.
In a distant future we would like to remove support for __defineGetter__ and __defineSetter__, after ES5 adoption has taken off, so as not to distract from the standardized support. The less new web developers have to know about legacy extensions superseded by standardized alternatives, the better. This action is at least several years in the future, likely longer; being able to make the change will require preparation and adjustment in anticipation of that time.



 

Friday, March 22, 2013

Tuesday, February 19, 2013

Javascript Basics Tutorial Part 8: Delegate Function

Delegate Function: A method declaration passed as a argument value in funtion.

Chapter 8
Output

Javascript Basics Tutorial Part 7: Module Design Pattern

Module Design Pattern: View code to understand the pattern.
Chapter 7:


Output
 

Javascript Basics Tutorial Part 6 : Nested Function

Nested Function---> Outer Inner function.

Semantics
function Outer(n)
{
      function Inner()
      {
          do something with (n);
          return n;
      }
      return Inner// Call Inner function;
}

Outer(10); //VALID  CALL
Inner(); //INVALID CALL.

Chapter 6:



























Output:



 

Javascript Basics Tutprial Part 5: Self Calling Or Immediate function.

Lets look at syntax representation of Self calling or Immediate function call.

Method 1
(
        function ()
       {
             something;
       }
)
( ) ;//This is self fn call

Method 2

(
      function ()
     {
          something;
      }

      ( )
) ;

Method 3
(
function  Anything()
{
something;
}

( )
) ;

The only difference is ( ) is inside or outside in the example above.
Chapter 5



Output

 

Monday, February 18, 2013

Javascript Basics Tutorial : Part 4 Var obj={};

Part 4 : var obj={};
Remember this semantics var X= {};

This chapter we will discuss how we can defined multiple methods and variable in OBJECT. The sample code describes the methods scope within OBJECTS and its declaration and semantics.
Understand diff between semantics and Syntax.

Chapter 4
Key notes here direct call to f1(), f2() and f() are INVALID. This is concepts of data encapsulation. Its implementations are hidden to outer world. Like we know how to drive car without knowing how it is internally deviced and operated.

Output


 

Javascript Basics Tutorial Part 3: Anonymous Methods

Anonymous Method Like C#.
Important Key notes:
  1. All Methods are funtions but funtions are not method.
  2. Methods can not be called before it is being defined. Unlike FUNCTIONS.
  3. Methods is represented as variable and function is assigned to it.
  4. Methods is variable and any var declaration must ends with semicolon.
  5. Methods can be declared as Anonymous with no name and can be declared with Named Expression.
var obj= function(){somthing;} ;

Chapter 3:

 Output
 

Javascript Basics Tutorial Part 2: Simple Function.

:In part 2 we are going to look into details of simple function declaration and its defination. We also look into function scope. Refer Part 1 for Objects and Array.

Function Scoping: Function can be called before it is defined. Look at below example.

Function : By default every function is like default constructor with inbuilt arguments.
We can also put debugger; to put a breakpoint and debug to step-in, step-out, step-over in vs 2010.

In short we can defined function with NO Input Argument but we can pass multiple input parameter values of any type while calling a function.
 
f2(17, 0.1, "Ninja", [], {});

function f2()
{
//Fn Responsibilty & Operations.
}
Interesting facts: Inside a function we can fetch the inputs values to the function through a array called arguments[].Internally it is stored in arguments[] array placeholder where we can reference and use the input values for the operations.




 Output

 

Javascript Basic Tutorial Part 1:Objects & Array

Here is the quick series of javascript begineer kit.
To make learning easy, below are the code demos with screenshot.
So lets get started

Objects & Array

All I have done is taken one default.aspx with all javascript references and one div tag to display results. We also have JQuery online reference just to have ready() function and few Jquery selector to create showresults() display panel.


Common Utility.JS

In order to simplify this kits, I have replaced alerts with ShowResults code snippet. There is a global array and global Method to display outputs. I'll be using ShowResults() Method to display output for each javascript demo.




Chapter 1. Objects & Array
  1. var obj={} represents objects
  2. var arr=[] represents array
The skeleton to define object are as given below. There are two ways to do it.
var dog={};
dog.breed='abc';
dog.bark= function(){
//some operations;
}

This defination involves comma separated property and method. The important note here is dog object is notated as a var defined as class with property and method. Always remember closure always ends with semicolon as it is assigned to var . Like
var animal= { something;};


var dog ={
breed:'abc', bark=function(){
}

}
};


Output 


Tuesday, January 22, 2013

Very Useful Jquery References


The best references


Six Things Every jQuery Developer Should Know
http://msdn.microsoft.com/en-us/magazine/ee730275.aspx

Object Oriented way of Jquery
http://msdn.microsoft.com/en-us/magazine/gg476048.aspx


How to Debug Your jQuery Code
http://msdn.microsoft.com/en-us/magazine/ee819093.aspx
http://milan.adamovsky.com/2012/04/on-april-26th-2012-i-presented-this.html

Unobstrusive Javascript
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

How to Create Your Own jQuery Plugin

http://msdn.microsoft.com/en-us/magazine/ff608209.aspx

Creating Responsive Applications Using jQuery Deferred and Promises
http://msdn.microsoft.com/en-us/magazine/gg723713.aspx

Introduction to Complex UIs Using jQuery UI
http://msdn.microsoft.com/en-us/magazine/hh127352.aspx

All In One Framework
http://www.elijahmanor.com/2010/06/my-7-jquery-articles-on-script-junkie.html

 

Object Oriented, functional and closure view of Jquery

Jquery =$

Well, I have been too much into Jquery. Being C# developer by nature its always been hard to adopt the style of programming in Jquery. What differentiate more is the style and modularization we have in C#. Apparently I like Jquery and try to code it as modular as I can.

Here is quick reference of MSDN magazine issue, Script Junkies....
http://msdn.microsoft.com/en-us/magazine/gg476048.aspx

Here you will understand following few important things.
  1.  Functional way of programming Jquery
  2.  Jquery Plugins
  3.  Objects in Jquery
  4.  Object-orientation through Closures
  5.  Object-orientation through Prototypes
  6.  Inheritance In Jquery
Functional Jquery:
  1. // Function to calculate a total
  2. var CalcTotal = function(x, y) {
  3. return x + y;
  4. };
  5. // Function to add taxes
  6. var AddTaxes = function(x) {
  7. return x * 1.2;
  8. };
  9. // Function that pipelines the other two
  10. var CalcTotalPlusTaxes = function (fnCalcTotal, fnAddTaxes, x, y) {
  11. return fnAddTaxes(fnCalcTotal(x, y));
  12. };
  13. // Execution
  14. var result = CalcTotalPlusTaxes(CalcTotal, AddTaxes, 40, 60);
  15. alert(result);
How to write Jquery plugins

  1. jQuery.fn = jQuery.prototype = {
  2. init: function( selector, context ) { ... },
  3. size: function() { return this.length; },
  4. each: function( callback, args ) {
  5. return jQuery.each( this, callback, args ); },
  6. ready: function( fn ) { ... }
  7. :
  8. }
Objects in Jquery

  1. var person = new Object();
  2. person.Name = "Dino";
  3. person.LastName = "Esposito";
  4. person.BirthDate = new Date(1979,10,17)
  5. person.getAge = function() {
  6. var today = new Date();
  7. var thisDay = today.getDate();
  8. var thisMonth = today.getMonth();
  9. var thisYear = today.getFullYear();
  10. var age = thisYear-this.BirthDate.getFullYear()-1;
  11. if (thisMonth > this.BirthDate.getMonth())
  12. age = age +1;
  13. else
  14. if (thisMonth == this.BirthDate.getMonth() &&
  15. thisDay >= this.BirthDate.getDate())
  16. age = age +1;
  17. return age;
  18. }
Object-orientation through Closures

  1. var Person = function(name, lastname, birthdate)
  2. {
  3. this.Name = name;
  4. this.LastName = lastname;
  5. this.BirthDate = birthdate;
  6. this.getAge = function() {
  7. var today = new Date();
  8. var thisDay = today.getDate();
  9. var thisMonth = today.getMonth();
  10. var thisYear = today.getFullYear();
  11. var age = thisYear-this.BirthDate.getFullYear()-1;
  12. if (thisMonth > this.BirthDate.getMonth())
  13. age = age +1;
  14. else
  15. if (thisMonth == this.BirthDate.getMonth() &&
  16. thisDay >= this.BirthDate.getDate())
  17. age = age +1;
  18. return age;
  19. }
  20. }
Object-orientation through Prototypes
  1. // Pseudo constructor
  2. var Person = function(name, lastname, birthdate)
  3. {
  4. this.initialize(name, lastname, birthdate);
  5. }
  6. // Members
  7. Person.prototype.initialize(name, lastname, birthdate)
  8. {
  9. this.Name = name;
  10. this.LastName = lastname;
  11. this.BirthDate = birthdate;
  12. }
  13. Person.prototype.getAge = function()
  14. {
  15. var today = new Date();
  16. var thisDay = today.getDate();
  17. var thisMonth = today.getMonth();
  18. var thisYear = today.getFullYear();
  19. var age = thisYear-this.BirthDate.getFullYear()-1;
  20. if (thisMonth > this.BirthDate.getMonth())
  21. age = age +1;
  22. else
  23. if (thisMonth == this.BirthDate.getMonth() &&
  24. thisDay >= this.BirthDate.getDate())
  25. age = age +1;
  26. return age;
  27. }
Inheritance In Jquery
By using the prototype feature you can achieve inheritance by simply setting the prototype of a derived object to an instance of the “parent” object.
  1. Developer = function Developer(name, lastname, birthdate)
  2. {
  3. this.initialize(name, lastname, birthdate);
  4. }
  5. Developer.prototype = new Person();