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 ofPerson.prototype
isObject.prototype
.boy.hasOwnProperty("name") //returns true.
This is an example of the prototype chain. In this prototype chain,Person
is the supertype forboy
, whileboy
is the subtype.Object
is a supertype for bothPerson
andboy
.Object
is a supertype for allObject
s in JavaScript. Therefore, anyObject
can use thehasOwnProperty
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);