Consider the following code:
function Robot(weapon) {
this.weapon = weapon;
this.fire = function() {
alert('Firing ' + this.weapon + 'projectile.');
};
}
var gunRobot = new Robot('gun');
vs.
function makeRobot(weapon) {
return {
weapon: weapon,
fire: function() {
alert('Firing ' + this.weapon + 'projectile.');
}
};
}
var laserRobot = makeRobot('laser');
So, if I understood right, the main difference between these two is that in the first example, gunRobot has a constructor property which points to Robot, whereas in the second example, laserRobot has a construtor property which points to Object. Both don’t add anything to their prototype, right?
Now, if I change the first example to:
function Robot(weapon) {
this.weapon = weapon;
}
Robot.prototype.fire = function() {
alert('Firing ' + this.weapon + 'projectile.');
};
var gunRobot = new Robot('gun');
gunRobot’s constructor property points to the Robot constructor, whose prototype property has a property fire. Now, if I call
gunRobot.fire();
as, gunRobot doesn not have a fire property, the next prototype up in the prototype chain is visited and checked for a fire property, right?
I’m mainly a Java programmer, so it’s quite hard to wrap my head around JS notion of object-orientation :-).
Really, really close, but considering this sentence…
…it seems that you may think that it is via the
constructorproperty thatgunRobotwill access itsprototypeobject.That wouldn’t be correct. The
gunRobotobject doesn’t have a property of its own calledconstructor, but that property is actually a member of theprototypeobject itself.The way that the
prototypeobject is referenced is internal and therefore implicit.This means…
You could shadow the
constructorproperty on thegunRobotobject, and still have your implicit reference to theprototypeobjectYou could delete the
constructorproperty from theprototypeobject, and theprototypechain would be unaffectedIf you entirely replace the
prototypeobject of the constructor, any objects that have already been created from the constructor do not see the change. Theirprototypeobject reference is permanent. Only new objects would have the internal reference to the newprototypeobject.And with respect to this question…
…you’re right that nothing has been added to the
prototypeobject of either object. (Of course, the defaultObject.prototypeobject has some default properties.)gunRobot—->Robot.prototype(empty object)Robot.prototype—->Object.prototypeObject.prototype—->nulllaserRobot—->Object.prototypeObject.prototype—->null