Inheritance - Quick JavaScript Interview Questions (2015)

Quick JavaScript Interview Questions (2015)

Chapter 1 Inheritance

Q. How to create a class?
ANSWER
JavaScript does not have a class definition. To mimic classes in JavaScript functions can be used to declare a class.

Example :
Let’s create a student class in JavaScript which takes two parameters name and roll as property. The code will look like below,

function Student(name,roll){ this.name = name;
this.roll = roll;

}

Q. How to create an object?
ANSWER
An object in JavaScript can be created using two ways:

New Keyword:
To create a student object from the above student class we can call the Student function using new keyword.

var student1 = new Student(‘sandeep’,2)

Anonymous Object:
Anonymous objects can be created using pair of curly braces containing property name and value pairs.

Var rose = {‘color’: ’red’}


Q. How to declare a private and a public member?

Private members are declared using var keyword and constructor function.

function Student(name,roll){ var id= ABCD123;
this.name = name;
this.roll = roll;

}

When a Student object will be created the propertied name and roll will be accessible using dot operator but id will not be accessible as it behaves as a private member and return undefined on call.

The above chrome console is showing a student1 object is created.name property is accessible as it is showing sandeep on student1.name call. So name is a public property for the student object. But id property is not accessible and returned undefined on student1.id call. This shows id is a private property in student1 object.

Q. What is prototype property?

By Using Prototype we can add new members to an existing object. Every JavaScript object has this property internally. Initially it is an empty object.

Example:

function Student(name,roll){
this.name = name;
this.roll = roll;

}
var student1 = new Student('sangeeta',30); Student.prototype.mark = 100;

Checkout the below chrome console for the use of protype.


Initially the student1 object has only two properties name and roll. By using prototype a new property mark has been added to student object with a value of 100.Now the console shows that the mark property is also added to the existing student1 object.

Q. What is constructor property?
ANSWER
Constructor property of an object maintains a reference to its creator function.
Example:
Let us checkout an example by creating a student object and calling the constructor property on it.

function Student(name, mark){
this.name=name;
this.mark =mark;

}
var student1 = new Student('sandeep',123); console.log(student1.constructor);

Checkout the following screen shot for above code in chrome console. The console log is printing the referenced function by student1 object.

Q. How to call other class methods?
ANSWER
Using call() and apply() method we can use methods from different context to the current context. It is really helpful in reusability of code and context binding.

call() : It is used to calls a function with a given this value and arguments provided individually.
apply(): It is used to call a function with a given this value and arguments provided as an array.

Below code has two function getTypeOfNumber() and getTypeOfAllNumber(). The details pf these functions are below. getTypeOfNumber : This method takes single number as
parameter and return the type either Even or Odd.
getTypeOfAllNumber : This method takes array of numbers
as parameter and return the types in an array with Even or
Odd.

var MyNumber = {
getTypeOfNumber : function(number){
var type = (number % 2 === 0) ? "Even" : "Odd"; return type;

},
getTypeOfAllNumber : function (){
var result = [],i=0;
for (; i < arguments.length; i++){
var type =
MyNumber.getTypeOfNumber.call(null,arguments[i]) ;
result.push(type)
}
return result;
}
};
var typeOfNumber =
MyNumber.getTypeOfNumber.call(null,21) console.log(typeOfNumber)
var typeOfAllNumber =
MyNumber.getTypeOfAllNumber.apply(null,[2,4,5,7 8,21])
console.log(typeOfAllNumber)

Below screenshot shows output of the above code Firebug console.


Q. Explain method overriding with an Example?
ANSWER
We can override any inbuilt method of JavaScript by declaring its definition again. The existing definition is accessible to override by the prototype property. Consider the below example, split() is an built-in method for a string object .Its default behaviour to break the specified string to an array and is a member function of String class. But we have overridden its definition using its prototype property.

Below screenshot shows the inbuilt behaviour of split() method. It has divided the string into an array of element.
The following screenshot shows the new overridden definition of split () method. It is now normally returns string “I am overriden”.

Q. How to inherit from a class?
ANSWER
Inheritance can be achieved in JavaScript using prototype property.

We need to follow 2 steps to create an inheritance.
Step1:
Child class prototype should point to parent class object.
<ChildClassName>.prototype = new <ParentClass>();
Step2:
Reset the child class prototype constructor to point self.
<ChildClassName>.prototype.constructor=<ChildClassName>

Example:
Below example shows ScienceStudent class as a child class of Student class. As the method showMyType() is available for ScienceStudent object.

function Student(name){
this.name=name;
}
Student.prototype.sayMyType = function(){
console.log("I am student type")
}
function ScienceStudent(name){
}
ScienceStudent.prototype = new Student();
ScienceStudent.prototype.constructor = ScienceStudent;
var student2 = new ScienceStudent('sangeeta');
console.log(student2.sayMyType());

Check out the below screen shot for the output of the above code in the developer console.


To test the type of an object belongs to a class or not instanceOf can be used. This returns a Boolean value, TRUE for an object belongs to a class or else FALSE. Check the below screen shot for the test of student2 object using instanceOf.

Q. What is differential inheritance?
ANSWER
Differential Inheritance is a common prototype-oriented model that uses the concept that most objects are derived from other, more generic objects, and only differ in a few small aspects. Each object maintains a reference to its prototype and a table of properties that are different.

Q. What is Object.create() method do?
ANSWER
ECMAScript 5.1 has this method in its specification. This method can be used to create a new object with given prototype object and properties. The syntax of this method is listed below.

Object.create(proto[, propertiesObject])

Example:
Below code has a Student class function with name property and the prototype object has a method getStudentName() which return the name of the student. A new student1 object has been creates using Object.create() method by passing the prototype object of Student with value of the name as sandeep. Then the getStudentName() method is called on student1 object and logged in the console.

function Student(name) {
this.name = name;
}
Student.prototype = {
getStudentName: function() {
return "Name of Student is :" + this.name; }
};

var student1 = Object.create(Student.prototype); student1.name = "Sandeep";
console.log(student1.getStudentName());

The following screenshot shows the output of the above code in the developer console.


Q. Write a polyfill for Object.create() method if it is not present in the browser?
ANSWER
ECMAScript 5.1 has this method in its specification. If the browser is old then Object.create() method is not present.To resolve this we need to write a polyfill. Below code shows the polyfill for Object.create() method.

//check if create method is present inside Object if (typeof Object.create != 'function') {
//define the create method
Object.create = (function() {
var Object = function() {};

return function(prototype) {

if (arguments.length > 1) {
throw Error('Second argument not supported');
}

if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}

Object.prototype = prototype;
var result = new Object();
Object.prototype = null;
return result; };
})();
}

The above code checks if the create() method is already present inside the Object using if condition and comparing its type to function. If this condition true it means the create() method is not present. Then the polyfill code block gets executes and assigns the empty object to Object.create property.

Q. What is the purpose of Object.defineProperties() method? ANSWER
ECMAScript 5.1 provides Object.defineProperties() method to create new properties to a defined object. It provides many configuration options to initialize these members. Below code shows the use of this method.

function Student(name) {
this.name = name;
}
var student1 = Object.create(Student.prototype),
properties ={
"subject": {
value: "Computer",
writable: true,
enumerable:true
},
"marks": {
value: 0,
writable: false,
enumerable:true
}
};
Object.defineProperties(student1, properties);
student1.name = "Sandeep";
student1.subject ="Mathematics";
student1.marks=75;
console.log(student1);

In the above code a student1 object created using Object.create() method. Then some new properties like subject and marks are added to this object. The enumerable option decided whether the property can be enumerated as own property. Writable property decides whether the property is modifiable or not. The value property takes the default value of the property. Below screenshot shows the output of the above code in the developer console.

Q. How can you distinguish scope and context in JavaScript? ANSWER
Scope pertains to the visibility of variables and context refers to the object to which a method belongs and can be changed by using call or applies.

Q. What are two ways in which the variable can be assigned to an empty object?
ANSWER
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. The syntax of creating empty object is listed below.

var aEmptyObject= new Object();
var aEmptyObject= = {};