Answer the question
In order to leave comments, you need to log in
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
Object.prototype.hash = function(string) {
return string.split('.').reduce(function(p,n) {
return p && p[n];
}, this);
};
)Object.prototype.hash = function(string) {
var obj = this;
string.split(".").forEach(function(el) {
try {
obj = obj[el];
}
catch(e) {
obj = undefined;
}
});
return obj;
}
Answer the question
In order to leave comments, you need to log in
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',
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question