I've recently discovered the whole debate regarding new
vs. Object.create()
. Coming from doing a ton of OO with new
I've learned certain patterns of how to solve my problems. With the intent of learning something different I thought I'd rewrite some simple "classical OO" code to the Object.create()
style.
I've run into the problem of nested objects, e.g.
new
function Base() {
this.name = { first: '', last: '' };
}
var a = new Base();
var b = new Base();
a.name.first = 'Sally';
a.name.last = 'Broker';
b.name.first = 'Peter';
b.name.last = 'Davis';
document.write('first:', a.name.first, " last:", a.name.last); // Outputs { first: 'Sally', last: 'Broker' }
document.write("<br>");
document.write('first:', b.name.first, " last:", b.name.last); // Outputs { first: 'Peter', last: 'Davis' }
Object.create()
var base = {
name: {
first: '',
last: ''
}
};
var a = Object.create(base);
var b = Object.create(base);
a.name.first = 'Sally';
a.name.last = 'Broker';
b.name.first = 'Peter';
b.name.last = 'Davis';
document.write('first:', a.name.first, " last:", a.name.last); // Outputs { first: 'Sally', last: 'Broker' }
document.write("<br>");
document.write('first:', b.name.first, " last:", b.name.last); // Outputs { first: 'Peter', last: 'Davis' }
I understand why the assignments to the nested objects don't work the same, and also that my thinking is based on coding patterns used in "classical OO". I'm trying to learn how I'm supposed think, design wise, when attacking something where I'd have gone for nested objects, but in terms of best practices for Object.create()
.