Tags: #js
var people,
person = {
names: ['James', 'Neil', 'Russ', 'Stuart']
};
function extend(destination, source, overwrite) {
var overwrite = overwrite || false;
for (var i in source) {
if (source.hasOwnProperty(i)) {
// If we're not allowed to overwrite an existing property…
if (!overwrite) {
// …then we check to see if the property is undefined…
if (destination[i] === undefined) {
// …if it is then we know we can copy the property to the destination object
destination[i] = source[i];
}
} else {
destination[i] = source[i];
}
}
}
return destination;
}
people = {
names: ['Ash', 'Brad', 'Mark', 'Mike'],
speak: function(which) {
console.log('Hi, my name is ' + this.names[which]);
}
};
// Composition not Inheritance
people.speak.call(person, 1); // Neil
// Composition via Mixin
extend(person, people, true); // leaving off the 3rd argument means we can can't overwrite the 'names' Array as it already exists
person.speak(1); // Brad
console.log('person has been extended', person);