Javascript concepts

Demonstrating some of Javascript's core concepts

by eitanp461

JavaScript

// loose typing
let x = 'foobar';
x = 3;
console.log(x); // 3

// dynamic objects
let student = {
	name: 'Bill'
};
student.age = 25;
console.log(student.age) // 25

// prototypical inheritance
function Person(first, last, age) {
  this.first = first;
  this.last = last;
  this.age = age;
};
/* Teacher extends Person */
function Teacher(first, last, age, subject) {
	Person.call(this, first, last, age);
  this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;

var teacher = new Teacher('Homer', 'Simpson', 42, 'life science');
console.log(teacher.first, 'teaches', teacher.subject); // Homer teachs life science
/* Prototype can change dynamically */
Person.prototype.shout = function() {
	return 'LOUD';
}
console.log(teacher.shout()); // LOUD