class sugar

Allen Wirfs-Brock allen at wirfs-brock.com
Mon Jun 6 10:58:21 PDT 2011


On Jun 5, 2011, at 7:50 PM, Christopher M. Balz wrote:

> Are there proposals for fixing, without going as far as making a 'class' system, the major drawback of prototype-based inheritance: Without something like a JavaScript (js) class factory (a class factory as provided by most js frameworks) to provide inheriting instances their own copies of mutables (objects, as distinguished from immutables such as strings, numbers, and functions), all inherited mutables are always shared by all inheriting instances, even when modified by a single inheriting instance.  The problem does not exist with immutables, as unique copies are bestowed upon an inheriting instance (as I understand it) if and when it modifies the property.
> 
> ...
> Summing up, it seems that adding 'class', while very helpful for the vast majority of developers who have been trained in Java and C++, does stray far from the original intent of simplicity of what I understand to be one of the inspirations for JavaScript, 'Self' (e.g., "Self: The Power of Simplicity", http://labs.oracle.com/self/papers/self-power.html).   And the center of gravity may have shifted toward JavaScript enough that 'class' may no longer be as needed by the user community as it was even a couple years ago.  So I think it would be better if 'class' could be avoided and instead, the few drawbacks I mention above fixed with some choice keywords (for example, a keyword to mark a mutable (object) property of a prototype instance such that inheriting instances would get their own unique copies of it).  That would enable many or most of the benefits of a 'class' system, while preserving the simplicity of the unity of type and instance that was
> one of the original selling points of 'Self'.  

In self, this problem seems to be address by the object creation convention.  New objects are created by invoking the "copy" method on the intended prototype object.  Every such object is expected to define an appropriate copy method that takes care of copying non-sharable mutable state. In JavaScript terms:


Object.prototype.copy = function () {return Object.create(this)};

var Polygon = {
   vertices: [{x:0,y:0}, {x:1,y:0}, {x:1,y:1}],  //default is a unit right triangle
   copy: function() {
        var newPoly = super.copy();  //proposed for ES.next, in ES 3/5 say: Object.prototype.copy.call(this)
        newPoly = this.vertices.copy();
    }
}

var mySquare = Polygon.copy();
mySquare.vertices[3]={x:0,y:1};

Allen




More information about the es-discuss mailing list