Sunday, 19 April 2015

JS QUESTIONS

****************************************************************
ISSUES WITH CLOSURE

function createFunction(){

var arr =  new Array();
for (var i = 0; i<=10; i++){
arr[i] =  function(){
return i;
}
}
return arr;
}


function createFunction(){

var arr =  new Array();
for (var i = 0; i<=10; i++)
{
arr[i] =  function(num)
{
return function()
{
return i;
}
}(i)
}
return arr;
}

*********************************************************
var Parent =(function(){
   var count = 0;
   var that = this;
   var __construct = function Person(pName){
       that.name = pName;
   }
   __construct.prototype.sayHello =  function(msg){
      return that.name + " " + msg + "!!!";
   }
   __construct.getCount = function(){ return count++;}
  return __construct;
})()

var Child = (function(){
     var __childConstruct =  function Child(){}
      __childConstruct.prototype =  Parent.prototype;
      __childConstruct.prototype.childMethod =  function(){ return "child scope";}

     return __childConstruct;
 

})()

***********************************************************

// x is a method assigned to the object using "this"
var A = function () {
    this.x = function () {
        alert('A');
    };
};
A.prototype.updateX = function(value) {
    this.x = function() {
        alert(value);
    }
};

var a1 = new A();
var a2 = new A();
a1.x();  // Displays 'A'
a2.x();  // Also displays 'A'
a1.updateX('Z');
a1.x();  // Displays 'Z'
a2.x();  // Still displays 'A'



**********************************************************************************

//anonymous functions are not bound to  the object in "this" context ...  meaning this object point to "window" in non-strict mode else "undefined" in strict mode

convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.

var name = “The Window”;
var object = {
name : “My Object”,
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};

**********************************************************************************

QUESTION:

console.log(sum(2,3));   // Outputs 5
console.log(sum(2)(3));  // Outputs 5

function sum(x) {
  if (arguments.length == 2) {
    return arguments[0] + arguments[1];
  } else {
    return function(y) { return x + y; };
  }
}

function sum(x, y) {
  if (y !== undefined) {
    return x + y;
  } else {
    return function(y) { return x + y; };
  }
}


 // When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored. On the other hand, if the number of arguments passed is less than the number of arguments in the function definition, the missing arguments will have a value of undefined when referenced within the function. So, in the above example, by simply checking if the 2nd argument is undefined, we can determine which way the function was invoked and proceed accordingly..

**********************************************************************************

QUESTION:


(function(){
  var a = b = 3;  // BEHIND THE SCENE :- b=3; var a= b;
})();

 
console.log("a defined? " + (typeof a !== 'undefined')); // non-strict mode false
console.log("b defined? " + (typeof b !== 'undefined')); // non-strict mode true


But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function..

Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)


**********************************************************************************

QUESTION:

BENEFITS OF 'use strict'


1) Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.

2) Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.

3) Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.

4) Disallows duplicate property names or parameter values. Strict mode throws an error when it detects a duplicate named property in an object (e.g., var object = {foo: "bar", foo: "baz"};) or a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.

5) Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems).

6) Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.


**********************************************************************************
CLOSURE:

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};

// Function defined , behind the scene ===> SCOPE CHAIN is created preloaded with GLOBAL VARIABLE OBJECT and saved to internal [[scope]] property.

 // Function called, behind the scene ===> EXECUTION CONTEXT is created and it's SCOPE CHAIN is built by copying the objects in function's [[scope]] property. After that LOCAL ACTIVATION OBJECT is created and pushed to front of context's scope chain.

 // SCOPE CHAIN :  is just pointer to variable objects


// GLOBAL VARIABLE OBJECT +  LOCAL ACTIVATION OBJECT

// In closures ==>  Function that is defined inside another function add the containing function ACTIVATION OBJECT into it's scope chain.


// Each function automatically gets two special variables as soon as function is called :  this +  arguments
 Inner function can not access these variables from outside function. It can be achieved by storing "this" in some variable which closure can access.

**********************************************************************************


(function() {
    console.log(1);
    setTimeout(function(){console.log(2)}, 1000);
    setTimeout(function(){console.log(3)}, 0);
    console.log(4);
})();


The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload event) while the browser is busy (e.g., processing an onclick), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload script is executed).

Similarly, setTimeout() also puts execution of its referenced function into the event queue if the browser is busy.

When a value of zero is passed as the second argument to setTimeout(), it attempts to execute the specified function “as soon as possible”. Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That’s why in the above example, the call to console.log(4) occurs before the call to console.log(3) (since the call to console.log(3) is invoked via setTimeout, so it is slightly delayed).

***********************************************************************************

var list = readHugeList();

var nextListItem = function() {
    var item = list.pop();

    if (item) {
        // process the list item...
        nextListItem();
    }
};

*************************************************************


var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;
    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();



(function(x){
  return function(y){
  return x;
  }
})(1)(2)

Wednesday, 18 June 2014

Inheritance in oopJs

//PARENT class

    function Parent()
    {
        var name =  "devesh"; //private variables
        this.pass = "123"; //public variables
        _protected = "protected";
        pro = "new proc";
       
        // private methods are declared within the scope of constructor   
        var privateMethod = function(){
        //var self =this
        // self.walk(); //accessing public methods in private method
        return console.log(name);
        }
        // privileged methods are methods that are public and same time have access to privated properties/methods   
        this.privilegedMethod = function(){
        return privateMethod();
        }

    }
    Parent.fixed = 3;
    // public methods   
    Parent.prototype.walk = function(){
    console.log("i am walking via public method");
    }

    Parent.prototype.sayHello = function(){
    console.log("say hello from parent");
    }

    //define child class
    function Child(){
    Parent.call(this) //call constructor of parent class
    }
    //var parentObj = new Parent({name:"devesh",pass: "1234", protect:"protected varibale"});
    Child.prototype = new Parent();  //Inherit parent class

    Child.prototype.constructor = Child // Correct constrcutor pointer as it was pointing to parent class

    Child.prototype.sayHello = function(){
    console.log("say hello from child");
    Parent.prototype.sayHello.call(this);
    console.log(self._protected);
    console.log(self.pro);
    console.log(self.name);
   
    //Parent.prototype.sayHello.call(this); way to call parent call method in child class....
    }

    Child.prototype.sayGoodBye = function(){
    console.log("good bye");
    }


    var childObj = new Child();   // Child.prototype = Object.create(Parent.protoype);

    childObj.sayHello();
    childObj.privilegedMethod();
    childObj.walk();
    console.log(childObj.fixed);
   

function Person(){
  if(Person.count == undefined){
    Person.count = 1;
  }
  else{
    Person.count ++;
  }
  console.log(Person.count);
}

var p1 = new Person();
var p2 = new Person();
var p3 = new Person();



//. In object oriented programing polymorphism is used to call the same method on different objects to have them respond in their own way.
function mainfuncone()
{
this.prop_1 =27;

}

mainfuncone.prototype.polyfuncname=function()
{
this.prop_1 += 10;
}

function mainfunctwo()
{
this.prop_11 =30;

}

mainfunctwo.prototype.polyfuncname=function()
{
this.prop_11 +=10;

}

obj1=new mainfuncone;
obj2=new mainfunctwo;

//call functions
obj1.polyfuncname();
obj2.polyfuncname();

//access properties values by using polymorphism
alert(obj1.prop_1);
alert(obj2.prop_11)

Design patterns implementation in oops JS + fibonocci series/ prime numbers using JS

// SINGLETON PATTERN ****************************

var Foo = function () {
    "use strict";
    if (Foo._instance) {
        //this allows the constructor to be called multiple times
        //and refer to the same instance. Another option is to
        //throw an error.
        return Foo._instance;
    }
    Foo._instance = this;
    //Foo initialization code
};
Foo.getInstance = function () {
    "use strict";
    return Foo._instance || new Foo();
}
   
    var obj1 = Foo.getInstance();
    var obj2 = Foo.getInstance();
   
    console.log( obj1 === obj2);
   
    // SINGLETON PATTERN ****************************
   
    var Foo2 = (function () {
    "use strict";
    var instance; //prevent modification of "instance" variable
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
        //Singleton initialization code
    }
    //instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    }
    return Singleton;
}());

    var obj21 = Foo2.getInstance();
    var obj22 = Foo2.getInstance();
   
    console.log( obj21 === obj22);
   
    // MODULE PATTERN ****************************
   
   
   
    var foo23 = (function () {
   
    "use strict";
    var instance;
    function aPrivateFunction() { console.log("i m private method");}
    return {
        foo23: function(){
            return instance = this
        },
        aPublicFunction: function () {
            aPrivateFunction();
            console.log("i m public method");
            }
        };
})();
//var myObj = new foo23();
foo23.customMethod =  function(){console.log("m custom method");};
foo23.aPublicFunction();
//foo23.aPrivateFunction(); //error
foo23.customMethod();

// A function that generates a new function for adding numbers

function addGenerator(num) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function (toAdd) {
        return num + toAdd
    };
}
// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number
var addFive = addGenerator(5);
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4
console.log(addFive(4));   // Which return true




var EmployeeModule = (function () {
    var employeeList = [];
    var allEmployee = function () {
        return employeeList;
    };
    var add = function (employee) {
        employeeList.push(employee);
    };
    var totalCount = function() {
        return employeeList.length;
    };
    return {
        add: add,
        getAll: allEmployee,
        totalCount: totalCount
    };
} ());






function Animal() {

  var walked = false

  function walk() {
    console.log('walking...')
    walked = true
  }

  function hasBeenWalked() {
    console.log(walked);
  }

  return {
    walk: walk
  , hasBeenWalked: hasBeenWalked
  }
}




function Cat() {
  var cat = {}
  var walked = false

  cat.__proto__ = Animal();

  cat.pat = function pat() {
    console.log('being patted')
  }

  cat.lasagna = function lasagna() {
    console.log('Lasagna!')
    walked = true
  }

  return cat
}
var garfield = Cat();
garfield.hasBeenWalked();
 garfield.walk();
 garfield.hasBeenWalked();


 function fibo(n) {
  var f = [];
  for (var c = 0; c < n; ++c) {
    f.push((c < 2) ? c : f[c-1] + f[c-2]);
  }
  console.log(f);
}
fibo(5);
function isPrime(i) {
  for (var c = 2; c <= Math.sqrt(i); ++c)
    if (i % c === 0) return false;
  return true;
}
function primeList(N) {
  var list = [];
   for (var i = 2; i != N; ++i)
     if (isPrime(i)) list.push(i);
  console.log(list);
}
primeList(10);

function MySingletonClass() {

  if ( arguments.callee._singletonInstance )
    return arguments.callee._singletonInstance;
  arguments.callee._singletonInstance = this;

  this.Foo = function() {
    // ...
  }
}

var a = new MySingletonClass()
var b = MySingletonClass()
console.log( a === b ); // prints: true



var foo = {x: 10};

var bar = {
  x: 20,
  test: function () {

    console.log(this === bar); // true
    console.log(this.x); // 20
   
    //this = foo; // error, can't change this value

    console.log(this.x); // if there wasn't an error, then would be 10, not 20

  }

};
bar.test();
foo.test = bar.test;
foo.test();

var a = {
  x: 10,
  calculate: function (z) {
    console.log( this.x + this.y + z);
  }
};

var b = {
  y: 20,
 
  __proto__: a
};

var c = {
  y: 30,
  __proto__: a
};

// call the inherited method
b.calculate(30); // 60
c.calculate(40); // 80


var x = 10;

(function foo() {
  var y = 20;
  (function bar() {
    var z = 30;
    // "x" and "y" are "free variables"
    // and are found in the next (after
    // bar's activation object) object
    // of the bar's scope chain
    console.log(x + y + z);
  })();
})();

Different ways to declare a function in Javascript

1)function A(){};             // function declaration
2) var B = function(){};       // function expression
3) var C = (function(){});     // function expression with grouping operators
4) var D = function foo(){};   // named function expression
5) var E = (function(){        // immediately-invoked function expression (IIFE) that returns a function
  return function(){}
})();
6) var F = new Function();     // Function constructor
7) var G = new function(){};   // special case: object constructor