this is the second step to understand the .prototype functionality.this is what I use to simulate the process:
function Person(name){ this.name = name; }
my_person_prototype = { getName: function(){ console.log(this.name); } };
in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:
a. first of all it makes an empty object, basically an empty hash like:
var newObject = {};
b. the next step that JavaScript takes is to attach the all prototype objects to the newly created object
we have my_person_prototype here similar to the prototype object.
for(var key in my_person_prototype){
newObject[key] = my_person_prototype[key];
}
It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.
now we can call the getName function in our my_person_prototype:
newObject.getName();
exactly similar to how you can call the JavaScript prototype based object.
c. then it gives that object to the constructor,
we can do this with our sample like:
Person.call(newObject, "George");
or
Person.apply(newObject, ["George"]);
then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.