How do I assign a function to the property of a Javascript object?
If the code was written like this, I bet you understand it:
var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: function() { alert('The name is '+ this.name) }
};
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: function() { alert('The name is '+ this.name) }
};
The author of the code wanted to define the "playerDetails()" function once.
Another way of showing this in a simplified manner is:
var player1 = {
name: "Chris",
score: 1000,
rank: 1
};
player1.playerDetails=function() { alert('The name is '+ this.name) }
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2
};
player2.playerDetails=function() { alert('The name is '+ this.name) }
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)
function playerDetailsFunc() {alert('The name is '+ this.name) }
var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: playerDetailsFunc
};
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: playerDetailsFunc
};
I'm still a newb myself, but you could create the method in the object as an alternative.
var player1= {name: "Chris", score: 1000, rank: 1, logDetails: playerDetails};
var player2= {name: "Kristofer", score: 100000, rank: 2, logDetails: playerDetails};
function playerDetails(){
console.log("The name of the player is "+ this.name + "."+ " His score is : "+ this.score + "and his rank : "+ this.rank);
}
player1.logDetails();
player2.logDetails();
Also, the link below under "Defining Methods" may help answer your question. enter link description here
Javascript functions are no different from other values or objects.
You can assign them to whatever you want; you can even pass them as parameters.