-
Notifications
You must be signed in to change notification settings - Fork 0
/
prototypeinheritance.js
37 lines (29 loc) · 1.24 KB
/
prototypeinheritance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function Plant()
{
this.country = 'Mexico';
this.isOrganic = true;
}
//Add the showNameAndColor method to the Plant prototype property
Plant.prototype.showNameAndColor = function()
{
console.log('I am a ' + this.name + ' and my color is ' + this.color);
}
//Add the amOrganic method to the Plant prototype property
Plant.prototype.amOrganic = function()
{
if(this.isOrganic)
console.log('I am organic baby!');
}
function Fruit(fruitName, fruitColor)
{
this.name = fruitName;
this.color = fruitColor;
}
// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.
Fruit.prototype = new Plant();
// Creates a new object, aBanana, with the Fruit constructor
var aBanana = new Fruit('Banana', 'Yellow');
// Here, aBanana uses the name property from the aBanana object prototype, which is Fruit.prototype:
console.log(aBanana.name); // Banana
// Uses the showNameAndColor method from the Fruit object prototype, which is Plant.prototype. The aBanana object inherits all the properties and methods from both the Plant and Fruit functions.
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.