我一直在努力寻找以下示例:
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();
我尝试过但不起作用。
然后他调用
player1.logDetails()
这是一个函数,但未在任何地方声明。(?)如果有人可以帮助?
先感谢您
最佳答案
如果代码是这样写的,我敢打赌您会理解的:
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()”函数。
另一种简化的显示方式是:
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函数来优化上面的代码,则它看起来就像您帖子中的代码。
如果我编写了代码块,则可能是这样写的:(这很容易阅读)
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 - 如何为Javascript对象的属性分配功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20826094/