Rob Eberhardt

cleverness ensues

skip navigation

 Friday, April 01, 2005

I just asked a guru of advanced Object-Oriented Javascript, Douglas Crockford the following question.  For posterity, and for other possible takers, I'm posting it here too.

Also, for the record, this has nothing to do with IE's proprietary -- but wonderful -- setExpression method or CSS expression capabilities.  Those dynamic properties only apply to DOM objects, not custom Javascript objects.


Do you know of a way to define dynamic object properties in Javascript?

For example, VBScript lets us define classes such as this:

CLASS myClass
    PUBLIC phrase
    PUBLIC PROPERTY GET firstword    'get first word from phrase
        firstword = left(phrase, instr(phrase, " "))
    END PROPERTY
    PUBLIC PROPERTY LET firstword(v) 'set phrase's new first word
        phrase = v & " " & phrase
    END PROPERTY
END CLASS

This demonstrates two important features:
1. the firstword property can return dynamic results (depending on the current value of the phrase property). 
2. setting the firstword property can run other code (which dynamically prepends to the phrase property).

We can fully accomplish #1 (Property Get) in Javascript, by reassigning the toString method/property to a function like so:

function myConstructor(){
    var self = this;    //preserve object's context
    this.phrase = '';
    this.firstword = function(v){
        if(v){self.phrase = v + ' ' + self.phrase};    //LET
        return self.phrase.substring(0, self.phrase.indexOf(' ')); //GET
    }
    this.firstword.toString = this.firstword;
}

...But I've found no way to achieve #2 (Property Let or Set) in Javascript.  I can set firstword as a method, but setting the property value overwrites the method definition (and all subsequent GETs return that static value).

I've extensively searched, but found no answer (at least not before Javascript 2.0, which doesn't yet exist).  Any ideas from the experts?

Update: Douglas Crockford responded that he doesn't care for getter/setter properties, since "it allows simple assignment to have side effects, which I think works against reliability."  (I take that as a "No, it's not possible.")
    My current need is that I'm patterning my custom object after part of the DOM, whose objects certainly do have getter/setters.  I agree with Douglas that getter/setter side effects can be dangerous (esp. in the hands of a poor coder, as with any powerful code construct), but I think the use of methods -vs- getter/setter properties should be in the realm of "best practice" rather than a language limitation. 

4/1/2005 3:25 AM Eastern Daylight Time  #    Disclaimer  |  Comments [6]  |