I would like to start organizing my code properly, so I want to use object literals. In the following case, I'm doing a pseudo class. I would like that init()
could work as a constructor, but unfortunately, I'm not seeing how to set attributes based on object context.
var car = {
context : this,
wheels : 0,
color : '',
speed : 0,
init : (function(x){
console.log(x);
x.wheels = 4;
x.color = 'red';
x.speed = 120;
})(context)
};
console.log(car.color);
Object literals work for singletons. If you want an instantiable object, you'll need to learn how js oop works and just use function objects.
You can't immediately run a function like that whilst declaring an object literal. What you can do:
Which removes the need for:
...and offers the possibility for:[edit] What was I thinking? If you want more instances of Car, you'll have to use a real
constructor
function instead of an object literal:Which can be simplified to:
Or if you wanted to cling on to some
init
like function:But hey, what happened to my
context
? you may ask. Well, it turns out you didn't need it after all. Isn't javascript a beautiful and flexible language?It's best to use normal constructors for these kind of tasks.