1.Print setinterval method
2.How to override alert method
3.Associate array and nested array difference
4.We have an array inside the method. While calling the method it always returns the difference value
5.Abstraction in Javascript
6.Encapsulation in Javascript
7.math.float in Javascript
8.Call and Bind Difference
Window Object::
Not every object is a direct property of document object. Thinks like navigator.appName, navigator.appCodeName are property of window object
Anonymous Functions
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead of the function declaration.
Normal function declaration
function hello() { // function declartion alert('world'); } hello();
Anonymous function declaration
var anon = function() { // function operator alert('I am anonymous'); }; anon();
Anonymous functions are created using the function operator
The two most common ways to create a function in javascript are by using the function declaration or function operator. Anonymous functions are created using the function operator.If the function keyword appears first in the statement and is followed by a function name, the function is being created by a function declaration:
If the function keyword appears anywhere else, it is probably being used as a function operator:
When the function operator is called, it creates a new function object and returns it. Here’s an example that creates a function and assigns it to a variable called flyToTheMoon:
-
var flyToTheMoon = function() {
-
alert("Zoom! Zoom! Zoom!");
-
}
Anonymous functions are created at runtime
The function operator can be used anywhere that it’s valid to use an expression. For example you can use the function operator when a variable is being assigned, when a parameter is being passed to a function or in a return statement. This is possible because the function operator is always invoked at runtime.Function declarations are different. They are run before any of the other code is executed so the functions do not have to be declared before the code that calls them.
Function declarations can’t be used to create anonymous functions because they require the function to have a name. The function declaration uses the function name to add it as a variable in the current scope.
Single Inheritance ::
The Singleton object is implemented as an immediate anonymous function.
The function executes immediately by wrapping it in brackets followed by two additional brackets.
It is called anonymous because it doesn't have a name.
The getInstance method is Singleton's gatekeeper. It returns the one and only instance of the object
while maintaining a private reference to it which is not accessible to the outside world.
var Singleton = (function () { var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
String Reverse ::
<script type="text/javascript">
var my_str="Welcome to www.plus2net.com"
var i=my_str.length;
i=i-1;
for (var x = i; x >=0; x--)
{
document.write(my_str.charAt(x));
}
</script>
Bind ::
We use the Bind () method primarily to call a function with the this value set explicitly.
It other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked.
Using bind we can change any member variable in object variable explicity.
Example 1 ::
// Create an object that contains the original function. var originalObject = { minimum: 50, maximum: 100, checkNumericRange: function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } } // Check whether 10 is in the numeric range. var result = originalObject.checkNumericRange(10); document.write(result + " "); // Output: false // The range object supplies the range for the bound function. var range = { minimum: 10, maximum: 20 }; // Create a new version of the checkNumericRange function that uses range. var boundObjectWithRange = originalObject.checkNumericRange.bind(range); // Check whether 10 is in the numeric range. var result = boundObjectWithRange(10); document.write(result); // Output: true
Example 2 ::
// Define the original function with four parameters. var displayArgs = function (val1, val2, val3, val4) { document.write(val1 + " " + val2 + " " + val3 + " " + val4); } var emptyObject = {}; // Create a new function that uses the 12 and "a" parameters // as the first and second parameters. var displayArgs2 = displayArgs.bind(emptyObject, 12, "a"); // Call the new function. The "b" and "c" parameters are used // as the third and fourth parameters. displayArgs2("b", "c"); // Output: 12 a b c
Bind :: (Another definition)
Bind creates a new function that will have
this set to the parameter passed to bind()Here's an example that shows how to use
bind to pass a member method around that has the correct this:var Button = function(content) { this.content = content;
};Button.prototype.click = function() { console.log(this.content + ' clicked');}var myButton = new Button('OK'); myButton.click(); var looseClick = myButton.click; looseClick(); // not bound, 'this' is not myButton
ar boundClick = myButton.click.bind(myButton); boundClick(); // bound, 'this' is myButtonWhich prints out:
OK clickedundefined clickedOK clicked
bind allows-
Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.
- set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
- reuse methods
- curry a function
function getMontlhlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.
var rachel = {name:'Rachel Green', total:500};
Now, create a function that can be used again and again to deduct the fee from her account every month//bind
var getRachelFee = getMontlhlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
Now, the same getMonthlyFee function could be used for another member
with a different membership fee. For Example, Ross Geller has a 250
balance and a monthly fee of 25var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMontlhlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
The simplest use of bind() is to make a function that, no matter
how it is called, is called with a particular this value.
|
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// Create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
Functions ::
In JavaScript functions are first class citizens, like classes in OO languages.
You can define a function in the traditional way like this.
function eat(){ console.log("Eating"); }
You can invoke the eat() function even before you define it, as shown here.
eat();//Prints Eating
function eat(){ console.log("Eating"); }
Though JavaScript is an interpreted language, function definitions are run first, irrespective of where they are placed in the code. So you can invoke a function even before you define it like the eat() function call.
You can also assign a function to a variable like this:
var eat = function(){ console.log("Eating"); }
Though eat is defined to be a variable, you can still invoke it like a normal function call: eat(). But what you have to watch out for is that you cannot invoke the eat() function before defining the variable. The following code will throw an error if the function is declared as an expression.
eat();//Uncaught TypeError: Property 'eat' of object [object DOM Window] is not a function
var eat = function(){ console.log("Eating"); }
So what’s the use of assigning a function to a variable? You can pass the eat variable as an argument to otherfunctions, as shown below
Functions as arguments
function work(arg){ arg(); }
work(eat);
work(function(){console.log("Coding");});
the work() function accepts an argument which can be a reference to another function.We can then invoke the passed function using the arg() call. A function that accepts another function as an argument
is commonly referred as a Higher-order function.
Classes in JavaScript ::
JavaScript is a functional language. It doesn’t have classes like those in OO languages. You can treat functions as classes, and create objects, by using the new keyword. You can create function objects that you can
manipulate and pass around like objects. This feature can be used to write traditional OO code. Say you want to create a class with variables and methods in JavaScript. Instantiate it just as you would in C# or
Java. Let’s create a class Person with name and age attributes and an eat() method as shown below
Person class
function Person(theName,theAge){
this.name = theName; //public variable
this.age = theAge;
this.eat = function(){
console.log(this.name + " is eating");
}
}
If you now want to create an object of class Person and invoke its eat() method, you can use the new keyword just
as in other OO languages.
var p1 = new Person("Sam",23);
p1.eat(); //Prints Sam is eating
console.log(p1.age); // Prints 23
The new keyword creates an object from the Person function and returns a reference to the object. Notice the use of this keyword in the Person class. The this keyword binds a variable to the object that is created. You can treat this
keyword like a public variable
Javascript Closure::
Javascript Closure are useful to create callback function and run time objects.
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
return nameIntro + firstName + " " + lastName;
}
return makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson
Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture.Inheritance ::
- A class can inherit characteristics from another class.
A newly created object has the same characteristics as another object without explicitly duplicating its functionality.
Javascript supports single inheritance only.
Rule for single inheritance with prototype property.
- We cannot instantiate parent class method without prototype property.
- We can inherit parent class members by assigning parent class instance to child class.
- We can't use prototype property in instance variable/object of any class.
- We can use prototype property in class name only.
<head>
<title>Single Inheritance</title>
<h1>Single Inheritance</h1>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function Parent(){
}
Parent.prototype.sayHello = function(){
document.write("Parent Instance Say Hello <br/>");
}
Parent.prototype.sayBye = function(){
document.write("Child Instance Say bye <br/>");
}
Parent.AddWithoutPrototype = function(){ /* This Method won't work/instantiate unless prototype property is specified */
document.write("Method Without Prototype<br/>");
}
function Child(){
Parent.call(this);
}
// Inherit Parent
Child.prototype = new Parent();
// Correct child constructor pointer to child class because it points to parent
Child.prototype.constructor = Child;
Child.prototype.sayHello = function(){
document.write("Child Instance Say Hello <br/>");
}
Child.prototype.sayMorning = function(){
document.write("Child Instance Say Morning <br/>");
}
var par1 = new Parent();
var child1 = new Child();
child1.sayHello();
child1.sayBye();
child1.sayMorning();
par1.AddWithoutPrototype();
par1.sayHello();
</script>
</head>
<body>
</body>
</html>
Encapsulation - Data can be grouped together with functionality that operates on that data. This, quite simply, is the definition of an object.
Wrapping of data in single unit is called encapsulation. methods and properties in a class is called encapsulation.
Polymorphism ::
Poly means "many" and morphism means "forms". Different classes might define the same method or property
Polymorphism One interface may be implemented by multiple objects.
- The ability to call the same method on different objects and have each of them respond in their own way is called polymorphism.
<script type="text/javascript">
function Person(age, weight) {
this.age=age;
this.weight=weight;
this.getInfo=function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kilo.";
}
}
function Employee(age, weight, salary){
this.salary=salary;
this.age=age;
this.weight=weight;
this.getInfo=function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kilo " +
"and earns " + this.salary + " dollar.";
}
}
Employee.prototype= new Person();
Employee.prototype.constructor=Employee;
// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the object
// that 'obj' refer to.
function showInfo(obj) {
document.write(obj.getInfo()+"<br>");
}
var person = new Person(50,90);
var employee = new Employee(43,80,50000);
showInfo(person);
showInfo(employee);
</script>
Aggregation - One object can reference another object.
Prototype-based programming
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.Namespace
A namespace is a container which allows developers to bundle up all functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties and objects.Namespaces allow us to group code and help us to avoid name-collisions.
It is very important to note that there is no language-level
difference between regular object and namespaces as there is in some
other object-oriented languages.
The idea behind creating a namespace in JavaScript is simple: one
global object is created and all variables, methods and functions become
properties of that object. Use of namespaces also minimizes the
possibility of name conflicts in an application.// global namespace
var MYAPP = MYAPP || {};
// sub namespace
MYAPP.event = {};
Below is code syntax for creating namespace and adding variable, function and method:// Create container called MYAPP.commonMethod for common method and properties
MYAPP.commonMethod = {
regExForName: "", // define regex for name validation
regExForPhone: "", // define regex for phone no validation
validateName: function(name){
// Do something with name, you can access regExForName variable
// using "this.regExForName"
},
validatePhoneNo: function(phoneNo){
// do something with phone number
}
}
// Object together with the method declarations
MYAPP.event = {
addListener: function(el, type, fn) {
// code stuff
},
removeListener: function(el, type, fn) {
// code stuff
},
getEvent: function(e) {
// code stuff
}
// Can add another method and properties
}
// Syntax for Using addListener method:
MYAPP.event.addListener("yourel", "type", callback);
Instance ::// Tree is a constructor function because we will use new keyword to invoke it.
function Tree (typeOfTree) {}
// bananaTree is an instance of Tree.
var bananaTree = new Tree ("banana");
Constructor ::
Constructor is used to initialize the members of the class. constructor have the samename of the class name.
A constructor is used with the
new keyword:var Vehicle = function Vehicle() {
// ...
}
var vehicle = new Vehicle();
What happens when a constructor is called?
Whennew Vehicle() is called, JavaScript does four things:- It creates a new object.
- It sets the
constructorproperty of the object toVehicle. - It sets up the object to delegate to
Vehicle.prototype. - It calls
Vehicle()in the context of the new object.
new Vehicle() is this new object.Using the prototype Property
The JavaScript prototype property allows you to add new properties to an existing prototype:Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
person.prototype.nationality = "English";
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
person.prototype.nationality = "English";
Thanks admin, I have learned the core java concepts from blog. Really helpful to me and I have bookmarked this page for my future reference.
ReplyDeleteJAVA Training in Chennai | JAVA Training Chennai | JAVA J2EE Training in Chennai
70+ JavaScript Interview Questions To Hire Or Get Hired With
ReplyDeleteVery good explanation sir. Thank you for sharing
ReplyDeleteNodeJs Online Training
NodeJs Training