javascript – Declare object and its prototype in a JSON block – Education Career Blog

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?

,

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.

Leave a Comment