How do I assign a function to the property of a Javascript object?

Viewed 43889

I was looking and struggling to the following example:

var player1= {name: "Chris", score: 1000, rank: 1};
var player2= {name: "Kristofer", score: 100000, rank: 2};

function playerDetails(){
alert("The name of the player is "+ this.name + "."+ " His score is : "+ this.score + "and his rank : "+ this.rank);
}
player1.logDetails= playerDetails;
player2.logDetails= playerDetails;

player1.logDetails();
player2.logDetails();

As far as I know player1.logDetails is a property of player1 or a method of player1. So I can't understand how the author assigns a property to a function. Also I don't get why you would write it like that instead of : player1.logDetails= playerDetails(); which I have tried and doesn't work.

Then he calls player1.logDetails() which is a function but not declared anywhere.(?)

If anyone could help?? Thank you in advance

4 Answers

var player1= {name: "Chris", score: 1000, rank: 1};
var player2= {name: "Kristofer", score: 100000, rank: 2};

playerDetails = player => console.log( "The name of the player is "+ player.name + "."+ " His score is : "+ player.score + "and his rank : "+ player.rank);
player1.logDetails= playerDetails(player1);
player2.logDetails= playerDetails(player2);

Related