Object oriented programming is a programming paradigm invented back in the 1960'es in order to structure data in programs in a more productive way. One of the aims was to achieve high code reusability. The things of the program, eg, a person, was described in a so called class once, and then used to create instances, objects, all based on that one description. The description consists of properties, similar to variables, and methods, similar to functions. The methods could address the properties in various ways such as displaying them, change them, or use them in calculations, etc. The idea was, and is, that if you have modelled an object on the class with the described structure, this structure would be copied on to every object of the same class. This meant, by and large, that all objects of a certain class have the same structure, and the same properties, and methods, and differ only in state, ie, values of the properties.[6]
The following section is to be read if you have knowledge of object oriented programming, OOP in a conventionally object oriented programming language such as PHP or Java
A conventional OOP usage is illustrated by PHP as follows.
person.php
<?php
class Person {
public $first;
public $last;
function __construct($first, $last) {
$this->first = $first;
$this->last = $last;
}
function getFullName() {
return $this->first . ' ' . $this->last;
}
}
$niels = new Person('Niels', 'Larsen');
print($niels->getFullName() . '<br/>');
$anat = new Person('Anat', 'Larsen');
print($anat->getFullName() . '<br/>');
Person.java
/**
* @author nml
* Demo
*/
public class Person {
private String first;
private String last;
public Person(String first, String last) {
this.first = first;
this.last = last;
}
public String getFullName() {
return this.first + " " + this.last;
}
}
Persprog.java
/**
* @author nml
* Demo
*/
public class Persprog {
public static void main (String[] args) {
Person niels = new Person("Niels", "Larsen");
Person anat = new Person("Anat", "Larsen");
System.out.println(niels.getFullName());
System.out.println(anat.getFullName());
}
}
Compilation:
nmlX240 oojs $ javac Person.java nmlX240 oojs $ javac Persprog.java
Outputs:
nmlX240 oojs $ java Persprog Niels Larsen Anat Larsen
Syntactically objects in JavaScript look like the following.
oolit.js
"use strict";
/*
* oolit.js
* values from literals
*/
// JavaScript Object Notation
let Person0 = {}; // Ex0: Create an empty object
let Person = { // Ex1: Create literal object
first: "Niels",
last: "Larsen"
}
console.log(Person.first + " " + Person.last); // preferred syntax
console.log(Person["first"] + " " + Person["last"]); // alternative syntax
or
oolit0.js
"use strict";
/*
* oolit0.js
* values from variables
*/
let first = window.prompt('Enter first name');
let last = window.prompt('Enter last name');
let Person = {
first: first,
last: last
}
console.log(Person.first + " " + Person.last); // preferred syntax
console.log(Person["first"] + " " + Person["last"]); // alternative syntax
A JavaScript object is delimited by braces,
{}, and it consists of a comma separated list
of key-value pairs. The operator assigning values to the
keys is colon, :.
In other object oriented languages where variables are typed
we use the concept class to denominate
a complex type, ie a type that has multiple properties,
eg first, and last above.
JavaScript has recently, in ES6 (2015), been given that concept.
Let us see an example:
oocon.js
'use strict';
/*
* oocon.js
* instantiation by constructor
*/
class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
toString() {
return `${this.first} ${this.last}`;
}
}
let person = new Person('Niels', 'Larsen');
console.log(person.toString());
In this example, the
let person = new Person(first, last);
invokes the function
constructor(first, last);.
The word new is a keyword used precisely for
that, creating instances of a class. The instances are
objects.
Kyle Simpson says in [Sim20a]
The terms "object-oriented," "class-oriented," and "classes" are all very loaded full of detail and nuance; they're not universal in definition.
We will use a common and somewhat traditional definition here, the one most likely familiar to those with backgrounds in "object-oriented" languages like C++ and Java.
A class in a program is a definition of a "type" of custom data structure that includes both data and behaviors that operate on that data. Classes define how such a data structure works, but classes are not themselves concrete values. To get a concrete value that you can use in the program, a class must be instantiated (with the new keyword) one or more times.
fif1.js
"use strict";
/*
* fif1.js
*/
class Person {
constructor(first, last) { // defines constructor function
this.first = first; // gives state to properties
this.last = last;
}
toString() {
return `${this.first} ${this.last}`;
}
}
let niels = new Person("niels", "larsen"); // create object by invoking constructor
console.log(niels.toString()); // use method
let anat = new Person("anat", "larsen");
console.log(anat.toString());
console.log(anat.toString === niels.toString);
// if true js objects are efficient
// in that they share functions
// thereby not wasting mewmoryfif1.html>
<!doctype html>
<html>
<head>
<title>test obj</title>
<meta charset='utf-8'/>
<script src='./fif1.js'></script>
</head>
<body>
<h1>Test Class Pattern</h1>
<p>Check Ctrl-Shift-I</p>
</body>
</html>
The previous is in Kyle Simpsons words the new best practice. He differs from his first edition of the refenced work, where his pattern for best practice was different. Let us just add one more useful example:
notebook.js
'use strict';
class Page {
constructor(txt) {
this.txt = txt;
}
toString() {
return this.txt;
}
}
class Notebook {
constructor() {
this.pages = [];
}
addPage(txt) {
let page = new Page(txt);
this.pages.push(page);
}
toString() {
let s = '';
for (let page of this.pages)
s += page.toString() + '<br/>';
return s;
}
}
let mathNotes = new Notebook();
mathNotes.addPage('Euler\'s number is e');
mathNotes.addPage('i is the square root -1');
document.write(mathNotes.toString());
This example is based on a similar example in [Sim20a].
Now a word on syntax. The first examples display the full name on the console, and you may notice the two legal ways of doing it. Dot notation is called property access, and the notation with square brackets is called key access. The dot notation is, I think, considered best practice. The alternative notation is used when the key is dynamically changed in the program.
Indirectly you may notice that key access notation is identical to what in PHP is known as associative array notation. These arrays do not exist in JavaScript but you may use objects as if :)
Importantly names must be strings in literal notation. If they're not they will be coerced to strings. Names may be dynamic, and generated in the code, eg by concatenation.
[6] For the depth needed here there's an excellent article at https://en.wikipedia.org/wiki/Object-oriented_programming