-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprototype.js
More file actions
51 lines (38 loc) · 1.69 KB
/
Copy pathprototype.js
File metadata and controls
51 lines (38 loc) · 1.69 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function Foo() { }
Foo.prototype.bar = 1
const a = new Foo()
console.log(a.bar)
Foo.prototype.bar = 2
const b = new Foo()
console.log(a.bar)
console.log(b.bar)
Foo.prototype = { bar: 3 }
const c = new Foo()
console.log(a.bar)
console.log(b.bar)
console.log(c.bar)
/*
Prototypes are the mechanism by which JavaScript objects inherit features from one another. Basically, when you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found.
Here, we have added bar property to the prototype of Foo. However, in the first two instances viz. Foo.prototype.bar = 1 and Foo.prototype.bar = 2 we are just updating this property to a value thus this change affects both previously created objects and newly created objects.
In the last instance, we are actually replacing the the Foo.prototype to a new object which will break the prototype chain. Hence, only newly created objects beyond this will have bar as 3
*/
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
function Employee(name, position) {
Person.call(this, name);
this.position = position;
}
// Set up inheritance
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
// Add method to Employee
Employee.prototype.getRole = function() {
return this.position;
};
const john = new Employee('John', 'Developer');
console.log(john.greet()); // What's the output? =>
console.log(john.getRole()); // What's the output? =>