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 an Object.
By returning a new anonymous object, you override the expression that would be assigned to a by default, which is the Robot.
Try this line in each and you will see:
alert(a.constructor);
For the first one, you will see Object and the second, you will see the Robot function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With