JS Class Refresher

Javascript

Just a little refresher on setting up a JS class.

To simply create a new JavaScript class create a constructor function and include any properties inside of this. To add methods to the class use the prototype protocol ie. className.prototype.MethodName.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Human(name, age) {
	this.name = name;
	this.age = age;
}
 
Human.prototype.logInfo = function() {
	console.log("I am: " , this.name);
}
 
Human.prototype.promote = function() {
	this.age ++;
	console.log("My new age is: " , this.age);
}
 
Human.prototype.setAge = function(age) {
	this.age = age;
}
 
Human.prototype.getAge = function() {
	return this.age;
}

The Class can then be instantiated and used as follows:

1
2
3
4
5
6
7
8
var bill = new Human('Bill', 1984);
bill.logInfo();
bill.promote();
 
var murray = new Human('Murray', 2003);
murray.logInfo();
murray.promote();
murray.setAge(61);

No comments

Post a Reply