如何为Javascript对象的属性分配功能? [英] How do I assign a function to the property of a Javascript object?
问题描述
我一直在努力寻找以下示例:
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();
据我所知player1.logDetails
是player1的属性或player1的方法.
因此,我无法理解作者如何将属性分配给函数.
我也不明白为什么你会这样写而不是:
player1.logDetails = playerDetails();
我尝试过但不起作用.
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.
然后他调用player1.logDetails()
这是一个函数,但未在任何地方声明.(?)
Then he calls player1.logDetails()
which is a function but not declared anywhere.(?)
是否有人可以帮助?? 预先谢谢你
If anyone could help?? Thank you in advance
推荐答案
如果代码是这样写的,我敢打赌您会理解的:
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) }
};
该代码的作者希望一次定义"playerDetails()"函数.
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) }
因此,如果您只想编写一次playerDetails函数来优化上面的代码,则看起来就像您帖子中的代码.
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
};
这篇关于如何为Javascript对象的属性分配功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!