Hello!
I am having some trouble trying to understand javascript's constructors and prototypes.
For example, here there is some code extracted from the engine:
// Scene_Map
//
// The scene class of the map screen.
function Scene_Map() {
this.initialize.apply(this, arguments);
}
Scene_Map.prototype = Object.create(Scene_Base.prototype);
Scene_Map.prototype.constructor = Scene_Map;
Scene_Map.prototype.initialize = function() {
Scene_Base.prototype.initialize.call(this);
this._waitCount = 0;
this._encounterEffectDuration = 0;
this._mapLoaded = false;
this._touchCount = 0;
};
I'll try to explain what I currently understand: first it creates the object Scene_Map. Then, inside the
constructor (I'm calling constructor to anything that is inside the brackets in
"function Scene_Map()", please correct me if I'm wrong) the
intialize function later declared is called by
this.initialize.apply(this, arguments). Then, the
prototype of the object
Scene_Base is passed onto the protoype of the object
Scene_Map, thus inheriting its properties.
(I am aware what I've said could be utterly wrong, but describing how I read this code might help you to understand what I don't)
I always thought the prototype of a object was the same as the constructor, but apparently, I'm wrong.
For instance, I have no idea what is happening here:
Scene_Map.prototype = Object.create(Scene_Base.prototype);
Scene_Map.prototype.constructor = Scene_Map;
And also, why you can't put everything that there is on
Scene_Map.prototype.initialize inside the constructor of
Scene_Map? Like this:
function Scene_Map() {
function initialize() {
Scene_Base.prototype.initialize.call(this);
this._waitCount = 0;
this._encounterEffectDuration = 0;
this._mapLoaded = false;
this._touchCount = 0;
};
As you can see, there is a lot I don't know. I would be really thankful if someone could help me to understand how prototypes and constructors work, what they
truly are, and in what they differ.
Thanks!
