R
R
Rapen2016-10-14 18:33:30
JavaScript
Rapen, 2016-10-14 18:33:30

What is the working principle of the built-in method in the prototype?

There is a built-in hash method, the prototype of Object, which takes a string containing multilevel access. Here is an example:

obj = {
  person: {
    name: 'joe',
    history: {
      hometown: 'bratislava',
      bio: {
        funFact: 'I like fishing.'
      }
    }
  }
};

obj.hash('person.name'); // 'joe'
obj.hash('person.history.bio'); // { funFact: 'I like fishing.' }
obj.hash('person.history.homeStreet'); // undefined
obj.hash('person.animal.pet.needNoseAntEater'); // undefined

Here are two different implementations of hash, they do the same thing:
1)
Object.prototype.hash = function(string) {
  return string.split('.').reduce(function(p,n) {
    return p && p[n];
  }, this);
};

2
)Object.prototype.hash = function(string) {
  var obj = this;
  string.split(".").forEach(function(el) { 
    try {
      obj = obj[el];
    }
    catch(e) { 
      obj = undefined;
    }
  });
  return obj;
}

How does each work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Markus Kelvin, 2016-10-14
@mmxdesign

The meaning of the prototype is to write one function and bind it to a common type (parent type) and then the children (instance) of this parent can have access to a common one function .. wrote it once you use it everywhere ...
And regarding the implementation of hash, this is already clean to taste .. I understand the question about prototypes or about the hash method?
1) the method uses the reduce method which iterates through the list ['person', 'history', 'hometown'] and with each iteration inside the obj object is reduced by the part where the key matched...

1. первый заход: 
{
  person: {
    name: 'joe',
    history: {
      hometown: 'bratislava',
      bio: {
        funFact: 'I like fishing.'
      }
    }
  }

2. второй заход
{
history: {
      hometown: 'bratislava',
      bio: {
        funFact: 'I like fishing.'
      }
}

3. третий заход
{
 hometown: 'bratislava',
}

I hope the meaning is clear?
2) the forEach method also first splits the string into a list ['person', 'history', 'hometown']
and iterates with the first key, and if it finds it returns that object (in our case, person, then history, etc.) and on the second run already compares with the second key
All the magic happens in the callbacks, i.e. each time the obj inside the function is no longer the same obj as at the beginning of the function.. you can easily check this by console.log inside these functions...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question