How did it happen that the link on the prototype was lost?
How does one template work and the other not? In the second code, the prototype link is lost, is there a way to set the prototype link using the second template? Or am I doing it wrong?
It works
function Robot() {
this.weapons=5;
this.lives=5;
}
Robot.prototype.fireWeapon=function(){alert('weapons fired');};
var a=new Robot();
a.fireWeapon();
This does not 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();
source to share
This is because in the second example you don't Robot
, you have Object
.
By returning a new anonymous object, you are overriding the a
default expression that would be assigned , this Robot
.
Try this line in each one and you will see:
alert(a.constructor);
For the first, you will see Object
, and in the second, the function Robot
.
source to share
The javascript class doesn't need return
anything!
And if so, then it is equal to what it returns, and it is not a prototype class.
See the log for both of your functions: http://jsfiddle.net/maniator/UreSA/
source to share