Javascript对象将属性分配给属性

时间:2013-12-29 14:23:42

标签: javascript function object properties

我正在努力寻找下面的例子:

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()这是一个函数,但没有在任何地方声明。(?)

如果有人可以帮忙? 提前谢谢

4 个答案:

答案 0 :(得分:39)

如果代码是这样编写的,我打赌你理解它:

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
};

答案 1 :(得分:2)

Javascript函数与其他值或对象没有区别 你可以将它们分配给你想要的任何东西;你甚至可以将它们作为参数传递。

答案 2 :(得分:0)

我自己仍然是个新手,但你可以在对象中创建方法作为替代方法。

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();

此外,“定义方法”下面的链接可能有助于回答您的问题。 enter link description here

答案 3 :(得分:-2)

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