1/* Answer to: "javascript prototype explained" */
2
3/*
4 The prototype object is special type of enumerable object to
5 which additional properties can be attached to it which will be
6 shared across all the instances of it's constructor function.
7
8 So, use prototype property of a function in the above example
9 in order to have age properties across all the objects as
10 shown below:
11*/
12
13function Student() {
14 this.name = 'John';
15 this.gender = 'M';
16}
17
18Student.prototype.age = 15;
19
20var studObj1 = new Student();
21alert(studObj1.age); // 15
22
23var studObj2 = new Student();
24alert(studObj2.age); // 15
1//simply prototype means superclass
2
3function Student(name, age) {
4 this.name = name,
5 this.age = age;
6}
7
8var stu1 = new Student("Wasi", 20);
9var stu2 = new Student("Haseeb", 25);
10//this class is add in all of the objects
11Student.prototype.class = "Free Code Camp";
12
13console.log(stu1);
14console.log(stu2);
15
16
1function Person(name) {
2 this.name = name;
3}
4Person.prototype.getName = function() {
5 return this.name;
6}
7
8var person = new Person("John Doe");
9person.getName() //"John Doe"
1function Person(first, last, age, eye) {
2this.firstName = first;
3this.lastName = last;
4this.age = age;
5this.eyeColor = eye;
6}
7
8Person.prototype.nationality = "English";
9
10var myFather = new Person("John", "Doe", 50, "blue");
11console.log("The nationality of my father is " + myFather.nationality)
1/*Prototype is used to add properties/methods to a
2constructor function as in example below */
3
4function ConstructorFunction(name){
5 this.name = name //referencing to current executing object
6}
7ConstructorFunction.prototype.age = 18
8let objectName = new ConstructorFunction("Bob")
9console.log(objectName.age) //18
1// prototypes in javascript, THey create new Methods to our constructor function
2const EmployersInfo = function(name , salary , bonusPercentage){
3 this.name = name ;
4 this.salary = salary;
5 this.bonusPercentage = bonusPercentage;
6}
7
8// prototype for getting the employer credential
9EmployersInfo.prototype.credentialInfo = function(){
10 return `${this.name} Has a base salary of ${this.salary}`;
11}
12
13EmployersInfo.prototype.getBonus = function(){
14 let bonusAmount = (this.salary * (this.bonusPercentage));
15 return `${this.name} earned ${bonusAmount} Bonus`;
16}
17// let's first create the instance of employerInform
18const employerInform = new EmployersInfo('kevin' , 12000 , 12);
19
20// logging employerInform
21console.log(employerInform);
22
23// logging the credentials
24console.log(employerInform.credentialInfo());
25
26// logging the Bonus function
27console.log(employerInform.getBonus());