javascript - Why use Object.create inside this reduce callback? -
so while working on #19 of fine tutorial - http://jhusain.github.io/learnrx/, find exercise works without using object.create. (see commented-out lines)
1. point of creating copy of accumulatedmap? other showing possible...
function() { var videos = [ { "id": 65432445, "title": "the chamber" }, { "id": 675465, "title": "fracture" }, { "id": 70111470, "title": "die hard" }, { "id": 654356453, "title": "bad boys" } ]; // expecting output... // [ // { // "65432445": "the chamber", // "675465": "fracture", // "70111470": "die hard", // "654356453": "bad boys" // } // ] return videos. reduce(function(accumulatedmap, video) { // object.create() makes fast copy of accumulatedmap // creating new object , setting accumulatedmap // new object's prototype. // new object empty , has no members of own, // except pointer object on based. if // attempt find member on new object fails, new object // silently attempts find member on prototype. // process continues recursively, each object checking // prototype until member found or reach first object // created. // if set member value on new object, stored // directly on object, leaving prototype unchanged. // object.create() perfect functional programming because // makes creating new object different member value // cheap changing member on original object! //var copyofaccumulatedmap = object.create(accumulatedmap); //copyofaccumulatedmap[video.id] = video.title; accumulatedmap[video.id] = video.title; //return copyofaccumulatedmap; return accumulatedmap; }, // use empty map initial value instead of first item in // list. {}); }
2 , if do using copyofaccumulatedmap
, end object this
which looks intriguing, puzzling because cannot same thing code here
var fruit = { 'taste' : 3 }; var apple = object.create(fruit); apple['size'] = 7; var apple = object.create(fruit); apple['hardness'] = 6; var apple = object.create(fruit); apple['weight'] = 10; console.log(apple.taste); console.log(apple.size); // undefined expect console.log(apple.hardness); // undefined expect console.log(apple.weight);
so allows object in exercise have chained prototypes doesn't allow apple same?
you kind of answered own question: object.create
makes prototype chain. object.create
takes parameter prototype object object being created.
var copyofaccumulatedmap = object.create(accumulatedmap);
the old accumulatedmap
being used prototype copyofaccumulatedmap
. copy returned, accumulatedmap
next time through.
Comments
Post a Comment