Update 1: I didn't mention this earlier, but I was trying to avoid using the new keyword. The Polyfill should work just fine, as well. I should have been clear that I was looking to see if there was an alternative way of writing similar code.
Chris Elliott's article 'Common Misconceptions about Inheritance in JS' illustrates a great way to use closures for data privacy, but does so with the ES6 method Object.assign.
He describes it as:
Object.assign()
is a new ES6 feature championed by Rick Waldron that was previously implemented in a few dozen libraries. You might know it as$.extend()
from jQuery or_.extend()
from Underscore. Lodash has a version of it calledassign()
. You pass in a destination object, and as many source objects as you like, separated by commas.It will copy all of the enumerable own properties by assignment from the source objects to the destination objects with last in priority. If there are any property name conflicts, the version from the last object passed in wins.
How can I write this sample without using the ES6 feature Object.assign?
let animal = {
animalType: 'animal',
describe () {
return `An ${this.animalType} with ${this.furColor} fur,
${this.legs} legs, and a ${this.tail} tail.`;
}
};
let mouseFactory = function mouseFactory () {
let secret = 'secret agent';
return Object.assign(Object.create(animal), {
animalType: 'mouse',
furColor: 'brown',
legs: 4,
tail: 'long, skinny',
profession () {
return secret;
}
});
};
let james = mouseFactory();