views:

16

answers:

1

I'd like to fake a namespace in Javascript. This can be done as follows:

var cars = {};
cars.car = function() {
    ...
}
cars.car.prototype = {
    drive: function() {
        ...
    }
}

Works fine. My question, however, is if I can directly fill the whole namespace with JSON, like this:

var cars = {
    car: function() {
        ...
    },
    car.prototype: {
        drive: function() {
            ...
        }
    }
}

That doesn't work. Can I somehow declare the prototype of car inside the car() function? Or is there another way to solve this?

A: 

Right off the bat, you need to use : (the "property assignment operator") instead of = (the "assignment operator") in a JSON object (JavaScript object literal). You also can't use a property accessor (. or []) on the left side of a property assignment in an object literal.

I think you need at least two statements in JavaScript to both (1) declare a function expression, and (2) assign its prototype. This would prevent you from being able to do what you describe ("directly fill the whole namespace with JSON). I'm not sure why you're trying to do this -- running two statements of JavaScript is fine for most purposes.

Zach
Oh, I just typed this down and made a mistake, sorry. Edited it.
jringots
Hm, thinking about your answer a bit, this is how it works in Clojure (one expression for the namespace and one function), so I guess it's fine. Is my first example how people usually do it?
jringots
The first example is how I would do it. Don't forget semicolons after the function expression assignments. :)
Zach
Another typo, sorry :) Anyways, thanks for answer.
jringots