top | item 13104022

(no title)

drewgross | 9 years ago

The difference is the JS has late binding.

  myObj.myMethod();
Has different semantics than

  var x = myObj.myMethod; 
  x();
Which causes code like:

  myList.map(myObj.myMethod);
to behave somewhat unintuitively.

discuss

order

groovy2shoes|9 years ago

Your examples don't need late binding to have different semantics — dynamic dispatch will suffice. That's not different from any other OO language (except perhaps in C++ for non-virtual methods). That's how we get polymorphism out of subtypes, after all: methods are resolved based on the dynamic value of the receiver at runtime, yielding single dynamic dispatch. Regardless of language, the `this` or `self` reference within a method always semantically behaves as if it were an additional parameter (except in typed languages where the variance under the subtyping relation is reversed, iirc), and is often implemented as such, albeit usually implicitly.

Of course, late binding implies dynamic dispatch, but the reverse isn't true. On the other hand, almost every untyped OO language uses late binding (I can't even think of one that doesn't, off the top of my head...), as do some typed languages (those that target the .NET CLR, for example), so even with your stronger assertion JS far from unique in that regard.

That behavior is standard fare for OO. If anyone finds it tricky, I find it more likely that the struggling programmer has yet to internalize OO than that JS is doing something strange (in this particular case, I mean... JS does plenty of strange shit otherwise ;) ).

spion|9 years ago

The difference is that JS has no binding, yet it still allows for first class methods. Thus the OO "illusion" (object owns the methods) is broken: there are no methods, just functions that take an argument named `this`, in a slightly weird way, only when attached to records.