Javascript - Objects


Objects in JavaScript are essentially key-value pairs. These pairs are called properties. Methods are properties that are functions. JavaScript is a prototype-based language. There is no distinction between classes and instances of those classes. This page does a good job of explaining the differences between a class-based (C++) and prototype-based (JavaScript) language.

var person = {
    fname: 'Dalton',
    lname: 'Cole',
    fullName: function() {
        return this.fname + ' ' + this.lname;
    },
    printName: function(func=console.log) {
        func(this.fullName());
    }
};

console.log(person.fullName());     // Dalton Cole
person.printName();                 // Dalton Cole

var person2 = new Object();
person2.fname = 'Dalton';
person2.lname = 'Cole';

// Shallow Copy
var person3 = Object.assign({}, person);

person.fname = 'Colton';
person['lname'] = 'Dal';

person.printName();     // Colton Dal
person2.printName();    // Dalton Cole

Constructor

function Person(first, last) {
    this.firstname = first;
    this.lastname = last;

    this.fullName = function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
}

let dalton = new Person('Dalton', 'Cole')
let colton = new Person('Colton', 'Dal')

dalton.fullName()
colton.fullName()

Prototype

The prototype property allows you to add new methods to object constructors.

function Person(first, last) {
    this.firstName = first;
    this.lastName = last;
}

Person.prototype.fullName = function() {
    return this.firstName = ' ' + this.lastName;
}

Person.property.fullName2 = () => this.firstName + ' ' + this.lastName; // Won't work as expected

let dalton = new Person('Dalton', 'Cole');
console.log(dalton.fullName());     // "Dalton Cole"
console.log(dalton.fullName2());    // "undefined undefined"