Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
  • 💬 Discuss
From the author of Objective-C in Smalltalk

Objective-C in Smalltalk

This year, I've written a compiler that translates Objective-C to JavaScript. The TypedArray extensions provided by WebGL make it easy to implement all of the low-level C types, but I wanted Objective-C objects to be mapped to JavaScript objects. The solution involved implementing a small Objective-C runtime in JavaScript.

Because Objective-C is a class-based language, I needed to implement a class-based object model in JavaScript. This was very simple: As with Smalltalk and Objective-C, I just added an isa field to every Objective-C object, pointing to the class. Objective-C classes are just objects in Objective-C (and they also have an isa pointer), so it made sense for them to be objects.

When you send a message to an object in Objective-C, it calls a function that looks a bit like the following simplified version (without the forwarding mechanisms) in JavaScript:

function objc_msgSend(object, selector)
{
    if (!object) return null;
    var method = object.isa.methods[selector];
    if (method)
        return method.apply(object, arguments);
}

A modern JavaScript implementation will inline this code, and via type specialization it will typically eliminate most of the code and turn it directly into a JavaScript method call. When forwarding is not being used, Objective-C message sends and JavaScript method calls run at about the same speed.

Each class' methods field is a JavaScript object. This object's prototype is the superclass' methods field. This means that you can add a method to one class and it will automatically be picked up by all subclasses. In a normal Objective-C implementation, this requires some fairly complex code, but in this version it's all done by the virtual machine (where it also requires complex code, but the person writing the class-based object model doesn't need to write it).

Using a similar mechanism, you could easily provide features such as multiple inheritance, method overloading, and so on. We've done a simple lookup, but nothing is stopping you from inspecting the types of all of the values in the arguments array and selecting a method based on that.

Although the syntax is slightly cumbersome, I hope that this article demonstrates that the semantics of JavaScript are sufficiently rich to implement class-based languages in relative ease. In contrast, implementing a prototype-based language in a class-based language takes a lot more effort.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus