Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come link to the protoype is lost?

Tags:

javascript

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();
like image 290
manraj82 Avatar asked Jan 20 '26 22:01

manraj82


1 Answers

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.

like image 63
Nicole Avatar answered Jan 23 '26 11:01

Nicole