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

I've been recently watching Structure and Interpretation of Computer programs, where it is demonstrated that first class functions and assignment operator with nested scope are enough to implement object oriented system.

The simplest example given is a Counter object. Translated from Lisp to Javascript it goes like this:

      function make_counter() {
        var val = 0;
        function get() {
          return val;
        }
        function inc() {
          val += 1;
        }
        return [get, inc]  
      }
    
      function get_count(counter) {
        return counter[0]();
      }
    
      function inc_count(counter) {
        counter[1]();
      }
    
      var counter = make_counter();
      console.log(get_count(counter).toString());
      inc_count(counter);
      inc_count(counter);
      console.log(get_count(counter).toString());
This gives polymorphism (you can define make_fast_counter() that increases by 2 and still use get_count() and inc_count() with it) and encapsulation (you can not decrease the count).


From http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m...:

The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures."

Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.

On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened.


There is a similar model in Lua by using closures for methods and upvalues for encapsulated state.




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

Search: