How do you define an OOP class in JavaScript?

JavaScript is Prototype based and not class based.

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as class-less, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.


I recommend this book for a concise, precise explanation of both how to use JS's prototypal inheritance as well as how to emulate classical OO inheritance in JS.

JavaScript: The good parts


Any function in javascript can be used to create an object:

Example:

function MyPoint(x, y) {
    this.x = x;
    this.y = y;
    this.distanceTo = getDistance;
}

function getDistance(p) {
  var dx = this.x-p.x;
  var dy = this.y-p.y;
  return Math.sqrt(dx*dx + dy*dy);
}

var p0 = new MyPoint(1, 2);
var p1 = new MyPoint(2, 3);

window.alert('The distance is ' + p0.distanceTo(p1));

Tags:

Javascript

Oop