Presume I have an object like this:
var Foo = {
x: 5,
sprite: new Image()
}
Problem: I want to initialize that sprite with the right src. However, when I use the following creation technique:
var f = Object.create(Foo);
I don't have a constructor method (aka init function) to setup sprite.src = 'cool.png';
My question:
If I am using the object literal technique, and Object.create()
, when do I actually initialize some of my internal state (like the example of the new Image()
)
My solution:
var Foo = {
create: function() {
var f = Object.create(Foo);
f.sprite.src = 'cool.png';
return f;
}
}
However, I don't know if that's a great pattern. I'd like to do this the "JavaScript Way" if there is a way. :)
Thanks!
To cut a long story short: Don't try. The basic idea of Object.create is avoiding constructor functions. You're better off using this good old pattern:
Then use
new Foo
instead ofObject.create
.