Thursday, March 20, 2014

javascript objects

In JavaScript not every data is an object. There exist a few primitive types, like strings, numbers and boolean which are not objects. For each of this types there exists a constructor which outputs an object with similar behavior: Number, String and Boolean. To confuse matters, one actually can call methods on primitive types - they will be converted to the corresponding objects during this operation, and then converted back. For instance one can do

var a = 4.1324;
a.toFixed(1) // outputs 4.1
Yet if you try to compare primitive types and objects with strict equality, the difference shows up

var a = new Number(4);
var b = 4;
a === b; // False!!!
typeof a; // 'object'
typeof b; // 'number'
Actually of one tries to compare objects, they turn out to be different anyway:

var a = new Number(4);
var b = new Number(4);
a === b; // False!!!
(From a conceptual point of view I sort of understand the distinction. Objects can have additional properties, hence the should not compare to equal unless they are actually the same. So if we want to have 4 === 4 we need to use a type which is not an object. But this dilemma is faced by any sufficiently dynamic programming language, yet Javscript is the only one I know where there are two types - one objectful and one not - for numbers or strings.)

Passing by Reference vs Passing by Value

It is critical to know whether a variable you are accessing has been passed by reference or value. Not knowing the difference can lead to spaghetti code and odd behavior that is difficult to troubleshoot.

Q:In JavaScript, are objects passed by reference or by value?

A:By reference

Explanation:
In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are passed by value.

JavaScript Interview Questions: Object-Oriented JavaScript
in Object-Oriented JavaScript.
Object Properties and Methods

In JavaScript, Objects have two things: properties and methods. Methods are simply properties that have a function assigned to them.

Q: What do you call an object’s property when it has been assigned to a function

A: A “method”

Q: True of False: A function can have its own properties and methods.

A: True

Explanation:
Functions inherit from Object. You can add properties and methods to a function at any time. Run the following code in your JavaScript console and you will see this behavior:


//create a function
function foo(){};
//assign a property
foo.color = 'red';
//assign a method
foo.sayHello = function(){
alert("hello!");
};
//inspect the object
console.dir(foo); //inspect the properties and methods of off
//execute the method
foo.sayHello();// "hello!"
//overwrite a method
foo.sayHello = function(){
alert("this is a different message");
};
//execute the method
foo.sayHello();// "his is a different message"
Object Syntax

There are different ways to access the properties of an object: bracket notation and dot notation. Care must be taken when deciding which syntax to implement as their behavior differs.

Q: What is the difference between using dot notation and bracket notation when accessing an object’s property?

A: If using dot notation, the property must be a string and refer to a property that exists. When using bracket notation, any valid JavaScript expression that produces a value can be used inside the brackets, such as a variable or an an array element.

Hint:

These are all valid lines of code:


foo = bar.name;
foo = bar["name"];
foo = bar[5 + 5];
foo = bar[ baz() ];
foo = bar[ baz[i] ];
Q: What is important to remember about the last property’s value in a JavaScript object literal?

A : The last property’s value should not be followed by a comma.

Hint: Most browsers will let you get away with it if you forget, but Microsoft Internet Explorer will complain about the extra comma.







Q: Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

?
1
2
3
var Foo = function(){
this.foo = "bar";
}
A: Foo is meant to be used as a constructor function

Q: Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

?
1
var Foo = function(){}
A:

?
1
var bar = new Foo();
Here is a jsFiddle.net example: http://jsfiddle.net/vs2Fg/

Creating Objects

There is more than one way to create an object in JavaScript. Which method you chose depends on the type of Object you need to create. For example, there is a difference between an Object Literal and and instance object in JavaScript. Also, while arrays are instances of the Array() constructor, they are still considered object.

Q:What are two ways in which the variable “foo” can be assigned to an empty object?

A:

var foo = new Object();
var foo = {};
Explanation:
When creating a new empty object, you can instantiate the Object() constructor, or you can simply create an empty object literal. In either case, you can then add properties to the new object.
Here is a jsFiddle.net example: http://jsfiddle.net/W6X2T/

Q: True or False: When you create an object literal, you must first instantiate the Object() constructor

A: False

Explanation:

In order to create an Object Literal, you assign a variable to an object. The syntax is as simple as var foo = {}. A constructor function is used when creating an instance object, which is a different process.

Q: True of False: You can only instantiate a JavaScript constructor function once.

A: False

Explanation: You can make as many instances as you want.

Q:When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

A:The DOM element that was clicked.

Helpful Links:

The value of this within the handler

Javascript – Advanced event registration models

Different Types of Objects

There is more than one type of object in JavaScript. Some examples are: Functions, Arrays, DOM objects and Date objects. Even NULL is technically an object, although it cannot be mutated.

Q: True or False: A JavaScript array is not an object

A: False

Explanation: JavaScript arrays are objects. They inherit from the JavaScript Object, and have methods and properties that are specific to arrays such as “length” and “sort”

Here is a jsFiddle.net example: http://jsfiddle.net/D2REh/

Q: If a string is a primitive value, why does it have a split() method?

A:
Because any string has a wrapper object that provides numerous methods for that type.

Explanation:
Although primitive JavaScript values do not enjoy the “first-class” nature of objects, they have wrapper objects that temporarily “wrap” the primitive value and provide various methods. Once a primitive wrapper’s method has finished executing, that primitive value is un-wrapped and returned to its normal primitive state.

Helpful Links:

Wrapper Objects | Javascript: The Definitive Guide
Minitech: The difference between primitive types and their object wrappers

Q: What is the name of the object that refers to the application used to view a web page?

A:
The “navigator” object

Q: Which object.property combination provides a reference to the protocol used to view the current web page?

A:
location.protocol

Q: True or False: The object returned by the document.getElementsByTagName() method is an array

A:
False

Explanation:
The object returned by the document.getElementsByTagName() method is an “HTMLCollection”. This is an array-like object that has a “length” property, can be enumerated, but is not an actual JavaScript array.

Helpful Links:

document.getElementsByTagName – Web API reference | MDN

HTMLCollection – Web API reference | MDN

Scope

Although the concept of scope in JavaScript pertains specifically to the visibility of variables, it is difficult to master object-oriented JavaScript without also mastering scope. The two work hand-in-hand, laying the groundwork for a very powerful and expressive language.

Q: True or False: An object literal can be used to create private variables.

A:
False. Only functions can be used in JavaScript to create privacy

Explanation:
All of the properties of a object literal are public and can be easily mutated. The only way to create private variable in JavaScript is by using a function. You can make a property of an object literal a function (i.e. a “method”), and use private variables in that function, but the named property will always be public.

Q: If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

A:
The window object

Explanation:
When omitting the “var” keyword, the variable you create becomes an “implied global”. But implied globals are not variables in a function. An implied global actually becomes a property of the window object. Although the window object is considered the “global” scope, it is an object, and any variable declared in the global scope (intentionally or otherwise), becomes a property of the window object.

Helpful Link:

Browser’s implied globals / Stoyan’s phpied.com

Context

In JavaScript, context pertains to the object within which a function is executed. Understanding context is a critical step towards writing advanced Object-Oriented JavaScript.

Q: What is the difference between a constructor function and a non-constructor function with respect to the word “this”

A: In a non-constructor function, “this” refers to the global context or if the function is executed inside of another function, it refers to the context of the outer function. In the instance object that is returned by a constructor function, “this” refers to the context of that function.

Explanation: JavaScript constructors are more useful when you understand how they behave differently from normal JavaScript functions and Object Literals.

Here is a jsFiddle.net example: http://jsfiddle.net/nyFyE/

Passing by Reference vs Passing by Value

It is critical to know whether a variable you are accessing has been passed by reference or value. Not knowing the difference can lead to spaghetti code and odd behavior that is difficult to troubleshoot.

Q:In JavaScript, are objects passed by reference or by value?

A:By reference

Explanation:
In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are passed by value.

Here is a jsFiddle.net example: http://jsfiddle.net/pmMLc/

Object Mutation

One of the things that makes JavaScript so expressive is its dynamic nature. Objects can be mutated at any time during the execution of your script. Those who come to JavaScript from conventional object-oriented languages such as C++ and Java sometimes find this behavior odd. One you become comfortable to working in this manner, you can start to tap into the deeper aspects of the language.

Q: True or False: Once you create an object, you can add, remove or change properties of that object at any time.

A: True

Explanation: JavaScript object are mutable.

Here is a jsFiddle.net example: http://jsfiddle.net/n3kR4/

Object Inheritance

JavaScript is a prototype-based language, which means that it differs from conventional object-oriented languages such as Java or C++. For example, when you create an array, it inherits from the Array constructor, which in-turn inherits from Object. You can create your own inheritance chain using the JavaScript prototype object.

Q: What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

A: The ‘prototype’ property.

Explanation:

Understanding JavaScript Prototypes. | JavaScript, JavaScript…

Q: How do you determine if a JavaScript instance object was created from a specific constructor or not?

A: Use the instanceof operator

Helpful links for the JavaScript instanceof operator:

https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof

http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript

http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/

http://javascript.gakaa.com/operators-instanceof.aspx

Constructors

When instantiated, constructors return an instance of themselves. It is important to understand the nature of an instance object as it differs from an object literal in a number of ways.

Q: Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

A: No.

Explanation:

A JavaScript constructor can only return an object. When no return value is specified, it returns an instance of itself. If an object is specified as the return value, then that object is the return value. If any value other than an object is specified as the return value, then it returns an instance of itself.

This chapter describes the predefined objects in core JavaScript: Array, Boolean, Date, Function, Math, Number, RegExp, and String.



What is the relationship between ECMAScript, Javascript and Jscript?
Javascript is the original name when the language was developed by Netscape.

JScript is Microsoft's name of their own implementation.

ECMAScript is the name of the language standard developed by ECMA, from the original Javascript implementation.

So, it's just one language, with different implementations.

Primitive Data Types in javascript
There are three primitive data type of interest to us:

numbers
strings
boolean values

Composite Data Types
All composite data types can be treated as objects, but we normally categorize them by their purpose as a data type.

Objects:

An object is a collection of named values, called the properties of that object. Functions associated with an object are referred to as the methods of that object.

Functions:

A function is a piece of code, predefined or written by the person creating the JavaScript, that is executed based on a call to it by name.

Arrays:

An Array is an ordered collection of data values.

JavaScript Object Literals

JavaScript also has two keyword literals that it considers to be objects. These are null and undefined.










How will you detect the type and version of a browser?
<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Browser Language: " + navigator.language + "</p>";
txt+= "<p>Browser Online: " + navigator.onLine + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>
output:
Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36

Cookies Enabled: true

Browser Language: en-US

Browser Online: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36

User-agent language: undefined

How do you usually get away with javascript errors in a web page?

Firefox firebug

Chrome developer tool ctrl+shift+j or f12

internet explorer f12

or http://www.jslint.com/




What is the use of innerHTML property?
<script>
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3Schools";
document.getElementById('myAnchor').href="http://www.w3schools.com";
document.getElementById('myAnchor').target="_blank";
}
</script>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
output:
Microsoft chnagelink(it is button), whenever we click on the button the above function is executed and replace the content inside the anchor tag

What is pattern?

A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications.

Simply put, a design pattern is a reusable software solution to a specific type of problem that occurs frequently when developing software. Over the many years of practicing software development, experts have figured out ways of solving similar problems. These solutions have been encapsulated into design patterns. So:

Types of Design Patterns

Creational patterns focus on ways to create objects or classes. This may sound simple (and it is in some cases), but large applications need to control the object creation process.

Structural design patterns focus on ways to manage relationships between objects so that your application is architected in a scalable way. A key aspect of structural patterns is to ensure that a change in one part of your application does not affect all other parts.

Behavioral patterns focus on communication between objects.

"1" == 1; true
"1" === 1; false
"1" == true; true
"1" === false; false

current version of javascript?
      1. relased in 2 years back





What’s relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined.
How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);
What does isNaN function do? - Return true if the argument is not a number.
What is negative infinity? - It’s a number in JavaScript, derived by dividing negative number by zero.

What boolean operators does JavaScript support? - &&, || and !
What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124.
How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach.
How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {};
How do you assign object properties? - obj["age"] = 17 or obj.age = 17.
What’s a way to append a value to an array? - arr[arr.length] = value;
What is this keyword? - It refers to the current object.

Q: What are Javascript closures?When would you use them?

A:
A closure is the local variables for a function – kept alive after the function has returned, or
A closure is a stack-frame which is not deallocated when the function returns.

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

The following code returns a reference to a function:
function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.

This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.
How do I append to an array in Javascript?

Use the push() function to append to an array:

// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];

// append new value to the array
arr.push("Hola");

// display all values
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
}

If you're only appending a single variable, then your method works just fine. If you need to append another array, use concat(...) method of the array class:

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar3);
Will spit out "1,2,3,4,5,6"

  • The append() method inserts specified content at the end of the selected elements.
Q: Replace the string "the lazy dog" with the string "the1 lazy2 dog3".

A:
// there are several ways to do this, .split or .replace both have good solutions to this
var statement = "The the lazy dog";
var statement_new = statement.split(' ').map(function(word, index) {
return word + index;
}).join(' ');
// OR
var i = 1,
sta = "The lazy dog";
sta.replace(/\w+/g, function(word) {
return word + i++;
});
//another method

'the lazy dog'.split(' ').reduce(function (p, c, i){ return (!+p ? p + ' ' : '') + c + (i + 1) }, 1)

No comments:

Post a Comment