JS-Inheritance & Prototypes.

Total Number of Questions: 4
  Inheritance using prototypes.

Create 2 objects - parent and child. Attach methods to parent and use those methods in child object using parents prototype

Code:-
const arr = [1,2,3,4,5,6];
const arrsum = {
	addAll:function(arr){
		let sum = 0;
		for(let i=0; i<arr.length; i++){
		  sum = sum + arr[i];
		}
		console.log(sum)
	  }
	}

Array.__proto__ = arrsum;
Array.addAll(arr);

  Prototype Chaining.

Write code to explain prototype chaining.

Code:-
function Person(name) {
  this.name = name;
}
let boy = new Person("Sam");
						  
Person.prototype.isPrototypeOf(boy); 
Object.prototype.isPrototypeOf(Person.prototype); 

Both of the above statements returns true, as a prototype is an object, a prototype can have its own prototype! In this case, the prototype of Person.prototype is Object.prototype.
						
boy.hasOwnProperty("name") //returns true.

This is an example of the prototype chain. In this prototype chain, Person is the supertype for boy, while boy is the subtype.
Object is a supertype for both Person and boy. Object is a supertype for all Objects in JavaScript.
Therefore, any Object can use the hasOwnProperty method.

  Method Inheritance.

Add a method to calculate sum of all elements in Array in array's protype, use that method to calculate sum for multiple arrays.

Code:-
const arr = [1,2,3,4,5,6];
const arrsum = {
	addAll:function(arr){
		let sum = 0;
		for(let i=0; i<arr.length; i++){
		  sum = sum + arr[i];
		}
		console.log(sum)
	  }
	}

Array.__proto__ = arrsum;
Array.addAll(arr);

  Print Inherited properties.

Write a JavaScript function to retrieve all the names of object's own and inherited properties.

Output:-
var student = {
    name : "Stu1",
    course : "Full-stack",
    rollNo : 49,
}
result = Object.keys(student)
console.log(result);