如何避免在团队成员中重新输入相同的功能?团队obj中的所有成员都可以使用say_name
函数。如何编写我的代码?
<script type="text/javascript">
var team={
// member
jimmy:{
name:'jimmy',
say_name:function (){}
},
darcy:{
name:'darcy',
say_name:function(){}
},
// common functions
say_name: function(){
// every member has the say_name function, I don't want to write the same code in each member. How to do?
alert('my name is ??')
}
}
</script>
答案 0 :(得分:2)
使用bind
:
var say_name = function () {
alert("my name is " + this.name);
}
var jimmy = {
name: 'jimmy',
say_name: say_name.bind(jimmy)
};
jimmy.say_name(); // my name is jimmy
虽然可能有更简单明了的方法。
答案 1 :(得分:1)
你可以使用原型,首先定义一个construtcor函数:
function Team(){
}
Team.prototype.say_name=function(){
// every team will have this method
}
建立一个团队:
var team=new Team();//now the team has a method called say_name
team.jimmy={name:'jimmy'}
更新:
这里有一篇关于javascript常用模式的精彩文章,非常值得一读:)
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
答案 2 :(得分:1)
制定这个答案花了一点时间。我想你想拥有多个具有变量名称等的多重播放器实例的团队实例。如果是这种情况,那么硬编码一个吉米成员就不是可行的了。
// object defenition
function Team(){
// property unuque for every team so teamB and teamC
// would not have the same members
this.members=[];
}
// properties shared by all team instances so teamB and teamC
// would refer to the same function
Team.prototype.addMember=function(name){
this.members.push(new TeamMember(name));
}
Team.prototype.getMember=function(name){
for(var i=0;i<this.members.length;i++){
if(this.members[i].name===name){
return this.members[i];
}
}
}
// Define a TeamMember, this is the definition, Bob would be
// and instance o TeamMember; like var Bob=new TeamMember("Bob");
function TeamMember(name){
this.name=name;
}
// properties shared by all TeamMember instance objects
// so bill and jane will point to this function
TeamMember.prototype.sayName=function(){
console.log("My name is:" + this.name);
}
// end of object definition
//creating instances
var teamB=new Team();
var teamC=new Team();
teamB.addMember("Tom");
teamB.addMember("Harry");
teamC.addMember("July");
teamC.addMember("Mary");
teamC.getMember("July").sayName();