How come one pattern works and the other doesnt? In the second code the link to the prototype is lost,is there any way of estabilishing the link to the prototype using the second pattern?Or am I doing it wrong?
This Works
function Robot() {
this.weapons=5;
this.lives=5;
}
Robot.prototype.fireWeapon=function(){alert('weapons fired');};
var a=new Robot();
a.fireWeapon();
This doesnt work
function Robot() {
var weapons=5;
var lives=10;
return {
weapons: weapons,
lives : lives
};
}
Robot.prototype.fireWeapon=function(){alert('weapons fired');};
var a=new Robot();
a.fireWeapon();
That is because it in the second example you don’t have a
Robot, you have anObject.By returning a new anonymous object, you override the expression that would be assigned to
aby default, which is theRobot.Try this line in each and you will see:
For the first one, you will see
Objectand the second, you will see theRobotfunction.