Methods in JavaScript

JavaScript supports methods defined on object types, which are similar to structs in some languages. Here’s an example:

// Define a 'rect' object type
class Rect {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    // This 'area' method is defined on the Rect prototype
    area() {
        return this.width * this.height;
    }

    // This 'perim' method is also defined on the Rect prototype
    perim() {
        return 2 * this.width + 2 * this.height;
    }
}

function main() {
    // Create a new Rect instance
    let r = new Rect(10, 5);

    // Here we call the 2 methods defined for our object
    console.log("area: ", r.area());
    console.log("perim:", r.perim());

    // In JavaScript, all object references are essentially pointers,
    // so there's no need for explicit pointer syntax
    let rp = r;
    console.log("area: ", rp.area());
    console.log("perim:", rp.perim());
}

main();

When you run this code, you’ll get:

area:  50
perim: 30
area:  50
perim: 30

In JavaScript, methods are typically defined as part of the class declaration. Unlike some languages, JavaScript doesn’t have a concept of value vs pointer receivers - all object references in JavaScript act like pointers.

JavaScript uses prototypal inheritance, which means methods are shared across all instances of a class. This is similar to how methods work in some other object-oriented languages, but with some key differences in how inheritance and method lookup work under the hood.

Next, we’ll look at JavaScript’s mechanism for defining interfaces, which involves using TypeScript or Flow for static typing, or implementing duck typing in vanilla JavaScript.