Note: This is not a question about classical and prototype inheritance. It's about what coding patterns to use to initialize objects. Class constructors create and initialize objects, whereas avoiding the new
operator and going for Object.create()
only creates the object and sets up the prototype chain. I have not yet found an online resource that explains best-practice coding patterns for doing creation and initialization when going for the Crockford Object.create()
approach.
If I have a constructor (in my head this makes my class, although I know classes don't technically exist yet in mainstream JavaScript)
function Person(first, last) {
this.name = {
first: first,
last: last
};
}
Person.prototype.tellName = function() {
return this.name.first + ' ' + this.name.last;
}
I can then instantiate it like this
var p1 = new Person('John', 'Doe');
var p2 = new Person('Sven', 'Svensson');
And change the Person.name.first
and Person.name.last
separately
p1.tellName(); // Output: 'John Doe'
p2.tellName(); // Output: 'Sven Svensson'
p1.name.first = 'Peter';
p2.name.last = 'Celery';
And execute the object's function Person.tellName()
with the following output
p1.tellName(); // Output: 'Peter Doe'
p2.tellName(); // Output: 'Sven Celery'
Which is very similar to how I'd approach building such a class in C++ or Java.
What patterns do I use to construct, or initiate an object where I can assign to a nested object when using the Crockford (Object.create()
-ish) approach instead of new
?
E.g.
...
// some code that does the same stuff as defining a class + constructor
...
var p1 = ???????
var p2 = ???????
// The following is the code and behavior I'm looking to get
p1.tellName(); // Output: 'John Doe'
p2.tellName(); // Output: 'Sven Svensson'
p1.name.first = 'Peter';
p2.name.last = 'Celery';
p1.tellName(); // Output: 'Peter Doe'
p2.tellName(); // Output: 'Sven Celery'