Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

OOP is an abstraction over functions, but it can be explained much more simply without closures. Classes introduce a convenient syntax / abstraction over polymorphism, and can be written with plain functions without the need for closures. Methods are just polymorphic functions that accept an implicit "self" argument, which is used to dispatch.

Taking the example from the article:

  function Person(firstName, lastName) {
    {
      type: "Person",
      fName: firstName,
      lName: lastName
    }
  }

  function getFullName(this) {
    switch(this.type) {
      case "Person":
        return this.fName + ' ' + this.lName;
      default:
        throw("TypeError getFullName is undefined for " + this.type ".")
    }
  }

  function setFirstName(this, firstName) {
    switch(this.type) {
      case "Person":
        this.fName = firstName;
        break;
      default:
        throw("TypeError setFirstName is undefined for " + this.type ".")
    }
  }
From here whenever a "method" is called, the program inspects the "type" attribute (this process is abstracted and hidden in OOP languages), and uses that to invoke the correct implementation of the method.

  let person = Person("John", "Foo");
  getFullName(person);


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: