-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructorExample.js
More file actions
26 lines (26 loc) · 965 Bytes
/
constructorExample.js
File metadata and controls
26 lines (26 loc) · 965 Bytes
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
function personConstructor(name, age) {
// an object literal that will be returned
const person = {};
// attributes of a person
person.name = name;
person.age = age;
// when attached to an object or instance, functions are called 'methods'.
// this is our first method, greet
person.greet = function(){
console.log("Hello my name is " + person.name + " and I am " + person.age + " years old!");
}
// finally, this function must return an instance
return person;
}
// create the 'steve' instance, run greet
const steve = personConstructor("Steve", 27);
steve.greet();
// create the 'anika' instance, run greet. note that it is different.
const anika = personConstructor("Anika", 33);
anika.greet();
// finally note how we can refine the greet method for any particular instance
const emily = personConstructor("Emily", 22);
emily.greet = function() {
console.log("I am the greatest, ever!");
};
emily.greet();