0

如何避免在我的团队成员中重新输入相同的功能?该say_name函数可供团队 obj 中的所有成员使用。如何编写我的代码?

<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>
4

3 回答 3

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

不过,可能有更直接的方法可以做到这一点。

于 2013-05-09T01:58:48.367 回答
1

你可以使用原型,首先定义一个构造函数:

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/

于 2013-05-09T02:06:28.653 回答
1

制定这个答案需要更长的时间。我认为您希望拥有多个团队实例以及具有变量名称等的多个玩家实例。如果是这种情况,那么对 jimmy 成员进行硬编码不是可行的方法。

// 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();
于 2013-05-09T02:17:50.253 回答