Javascript constructor and classes
old way and new way of making Javascript objects
by dshilkret
HTML
<div id="display_1"></div>
<br><br>
<div id="display_2"></div>
<br><br>
<div id="display_3"></div>
JavaScript
//html for the below javascript:
//<div id="display_1"></div>
//<br><br>
//<div id="display_2"></div>
//<br><br>
//<div id="display_3"></div>
//old school way of making an object: constructor function
//separate Person object constructor function
//from its behavior, AKA its prototype
//constructor function:
function Person (name, gender){
this.name = name;
this.gender = gender;
}
//prototype:
Person.prototype.sayHello = function(){
console.log("Hello, my name is "+ this.name);
return ("Hello, my name is "+ this.name);
}
//new Person:
var sarah = new Person("Sarah", "female");
//person instance, calling method, sayHello(); within the html element #display_1:
document.getElementById("display_1").innerHTML = sarah.sayHello();
///////////////
//new school way of making an object: ES6 class
//class, includes methods inside it, including constructor function:
class User {
constructor(name, gender) {
this.name = name;
this.gender = gender;
}
sayHello() {
console.log("Hello, my name is "+ this.name);
return("Hello, my name is " + this.name)
}
}
var bob = new User("Bobby", "male");
document.getElementById("display_2").innerHTML = bob.sayHello();
/////////
//can also extend a class, using extends:
class Teacher extends User {
// extending (AKA inheriting from) User when creating the new Teacher class.
// also overriding the sayHello method to output different words
sayHello() {
super.sayHello() //calling sayHello method of the superclass, AKA User
console.log("I am a teacher");
return("I am a teacher, and you can call me " + this.name);
}
}
var tom = new Teacher("Tom", "male")
document.getElementById("display_3").innerHTML = tom.sayHello();