Itzik984
Itzik984

Reputation: 16764

Unable to add to object prototype

I have this Object Literal:

var RPSPlayer = {....}

and I want to make new "children" from this object by using:

var player1 = new Player(randomPlay);

When I try to add a function to a Player prototype like this:

function Player(play) {
    this.prototype.play = play;
    return play;
};

I get an error.

play is a function returning a string which Player function gets as a parameter.

The problematic line is:

 this.prototype.play = play;

Upvotes: 0

Views: 105

Answers (2)

Raynos
Raynos

Reputation: 169383

var RPSPlayer = {....}

and i want to make new "children" from this object by using:

var child = Object.create(RPSPlayer);

but when im trying to add function to player by prototyping using:

RPSPlayer.play = function () { ... }

it works!

Seriously though, use Object.create to create your instances and distinguish between own properties of instances and properties that belong on the prototype.

If you want an instance to have own properties then write to it

child.play = function () { ... }

Upvotes: 0

Ry-
Ry-

Reputation: 224896

It should be simply:

function Player(play) {
    this.play = play;
}

Player.prototype = RPSPlayer;

Upvotes: 1

Related Questions