Author: shahprashant
Way to create an object in Javascript
1) // object constructor
var mango = new Object (); mango.color = "yellow"; mango.shape= "round"; mango.sweetness = 8; mango.howSweetAmI = function () { console.log("Hmm Hmm Good"); }
2) // object literal
// This is an object with 4 items, again using object literal var mango = { color: "yellow", shape: "round", sweetness: 8, howSweetAmI: function () { console.log("Hmm Hmm Good"); } }
3) // constructor pattern
function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) { this.color = theColor; this.sweetness = theSweetness; this.fruitName = theFruitName; this.nativeToLand = theNativeToLand; this.showName = function () { console.log("This is a " + this.fruitName); } this.nativeTo = function () { this.nativeToLand.forEach(function (eachCountry) { console.log("Grown in:" + eachCountry); }); } } var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
4) // using prototype pattern
function Fruit () { } Fruit.prototype.color = "Yellow"; Fruit.prototype.sweetness = 7; Fruit.prototype.fruitName = "Generic Fruit"; Fruit.prototype.nativeToLand = "USA"; Fruit.prototype.showName = function () { console.log("This is a " + this.fruitName); } Fruit.prototype.nativeTo = function () { console.log("Grown in:" + this.nativeToLand); } var mangoFruit = new Fruit ();
5) // using Object.create()
var superHuman = { usePower: function () { console.log(this.superPower + "!"); } }; var banshee = Object.create(superHuman, { name: { value: "Silver Banshee" }, superPower: { value: "sonic wail" } }); // Outputs: "sonic wail!" banshee.usePower();
Difference between Object.create() and new SomeFunction()
The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.
Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)
http://adripofjavascript.com/blog/drips/basic-inheritance-with-object-create.html
http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction
Static Concept
A static variable is one that’s associated with a class, not objects of that class.
Static is an access qualifier that limits the scope but causes the variable to exist for the lifetime of the program. This means a static variable is one that is not seen outside the function in which it is declared but which remains until the program terminates. It also means that the value of the variable persists between successive calls to a function.
void fun() { static int fnvalue=0;//Executed once printf(" \n%d",fnvalue++);// Value changed retains for next call }
By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class.
Features of Object Oriented Programming
Encapsulation:
Encapsulation is a mechanism by which you restrict the access to some of the object’s components, as well as binding the data and methods operating on the data. Encapsulation is a way to obtain ‘information hiding’.
Abstraction:
Abstraction is the process of moving from a specific idea to a more general one. For example take your mouse. “Silver Logitech MX518” is a concrete, specific item, and “mouse” is an abstraction of that.
Inheritance:
Polymorphism:
Displaying multiple behavior. Achieved via virtual functions, operator overloading, function overloading, etc
Virtual Function: Without “virtual” you get “early binding”. Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through. With “virtual” you get “late binding”.
Virtual Constructor:
Stack vs Heap
The Stack
What is the stack? It’s a special region of your computer’s memory that stores temporary variables created by each function (including the main()
function). The stack is a “LIFO” (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.
The advantage of using the stack to store variables, is that memory is managed for you. You don’t have to allocate memory by hand, or free it once you don’t need it any more. What’s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).
Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be stored on the stack. This is not the case for variables allocated on the heap.
To summarize the stack:
- the stack grows and shrinks as functions push and pop local variables
- there is no need to manage the memory yourself, variables are allocated and freed automatically
- the stack has size limits
- stack variables only exist while the function that created them, is running
The Heap
The heap is a region of your computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc()
or calloc()
, which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free()
to deallocate that memory once you don’t need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won’t be available to other processes). As we will see in the debugging section, there is a tool called valgrind
that can help you detect memory leaks.
Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.
Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
Stack vs Heap Pros and Cons
Stack
- very fast access
- don’t have to explicitly de-allocate variables
- space is managed efficiently by CPU, memory will not become fragmented
- local variables only
- limit on stack size (OS-dependent)
- variables cannot be resized
Heap
- variables can be accessed globally
- no limit on memory size
- (relatively) slower access
- no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
- you must manage memory (you’re in charge of allocating and freeing variables)
- variables can be resized using
realloc()
In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap.
https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html
Linked List : Mth to Last Element of a Linked List
Given a singly linked list devise an algorithm to find the mth-to-last element of the list.
http://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
Useful Coding Resources
- Williams Coding Book: http://wlcoding.blogspot.com/
Array Rotation
Rotate an n sized array by m
1) Method-1 : Use temp array
2) Method-2 : Rotate one by one
3) Method-3 : Rotate by GCD
http://www.geeksforgeeks.org/array-rotation/
4) Method-4 : Reversal algo
http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
Functional vs Procedural vs Object Oriented Programming
In a purely procedural style, data tends to be highly decoupled from the functions that operate on it. Procedural is a type of imperative programming style. An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.
In an object oriented style, data tends to carry with it a collection of functions.
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. A function is called ‘pure’ if all its inputs are declared as inputs – none of them are hidden – and likewise all its outputs are declared as outputs. Functional programming is about writing pure functions, about removing hidden inputs and outputs as far as we can, so that as much of our code as possible just describes a relationship between inputs and outputs. Let’s not hide what a piece of code needs, nor what results it will yield. If a piece of code needs something to run correctly, let it say so. If it does something useful, let it declare it as an output. When we do this, our code will be clearer. Complexity will come to the surface, where we can break it down and deal with it.