Simple prototyping in Python

Michael Geary Mike at DeleteThis.Geary.com
Fri Apr 30 17:26:53 EDT 2004


> Dave Benjamin wrote:
> > JavaScript has a syntax for this:
> >
> > var o = {a: 5, b: 6}

has wrote:
> Looks on the surface like AppleScript's record type, which
> is roughly analogous to C structs... and useless for anything
> more than struct-style usage. While I did read about JS
> programming in the dim-n-distant past - it was one of a
> number of languages I looked at when learning proto-OO
> on AS, which lacked any decent learning material on the
> topic - I've pretty much forgotten everything since. So can
> I ask: is the JS structure more flexible; e.g. can one add
> functions to it to operate like methods on the other data in
> the structure? Or does it have to provide a second structure
> for proto-OO use, as AS does?

A JavaScript object literal is simply a convenient way to construct an
object. You can put anything in that object that you can put in any other
object.

This object literal:

var o = { a: 5, b: 6 }

is just a shorthand for:

var o = new Object
o.a = 5
o.b = 6

In fact, if you do o.toSource() after either of those, you'll get the same
result:

({a:5, b:6})

As with any other object, you can put functions as well as data in an object
literal, e.g.:

var o =
{
    a: 5,
    incr: function() { return ++this.a },
}

o.incr() will return 6, 7, 8, etc. if you call it repeatedly.

As Dave mentioned, you can also use closures, as in this example which uses
both a closure and a property in the object literal:

function F()
{
    var c = 105;

    return {
        a: 5,
        incr: function() { return [ ++this.a, ++c ] },
    }
}

var x = new F
var y = new F
x.incr()
y.incr()

-Mike





More information about the Python-list mailing list