Skip to content
Advertisement

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

I was looking and struggling to the following example:

JavaScript

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

Advertisement

Answer

If the code was written like this, I bet you understand it:

JavaScript

The author of the code wanted to define the “playerDetails()” function once.

Another way of showing this in a simplified manner is:

JavaScript

So if you wanted to optimize the code above by only writing the playerDetails function once, it would look like the code in your post.

If I had written the code block, I might have written it like this: (which is easy to read)

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement