【问题标题】:javascript passing argument in objectjavascript在对象中传递参数
【发布时间】:2017-03-29 05:58:56
【问题描述】:

对不起,我太新手了,即使在观看了大量视频并且如此努力地查看 stackoverflow 之后,我什至无法完全理解,甚至无法正确找到我的问题(使用不同的对象传递参数?)所以在这里我将展示我的代码。

var Test1 = function(name,gender,job) {
  this.name = name;
  this.gender = gender;
  this.job = job;
this.say = function(name ,gender, job){
    console.log(" sup "+ name +", goodluck in" + job);
  }
}

这是new object

var budi = new Test1('Budi', 'male', 'developer');
var tono = new Test1('Tono', 'male', 'chef');

我想通过argumentobject

budi.say(tono);

【问题讨论】:

    标签: javascript object arguments


    【解决方案1】:

    你可以有say()的这个实现

      this.say = function(person){
        console.log(" sup "+ person.name +", goodluck in" + person.job);
      }
    

    或者这样称呼它:

    budi.say(tono.name, null, tono.job)
    

    【讨论】:

      【解决方案2】:

      你可能想要这样做

      this.say = function(/*no arguments here*/ ){
          console.log(" sup "+ this.name +", goodluck in" + this.job);
      }
      

      如果您将相同名称的参数赋予不同的作用域,它们将被视为不同的变量。像这样你可以这样做:

      var budi = new Test1('Budi', 'male', 'developer');
      budi.say();
      

      它会正确显示你在构造函数中使用的字符串。

      【讨论】:

        【解决方案3】:

        say() 方法中,从方法参数中读取namejob(在我的示例中为person):

        var Test1 = function(name, gender, job) {
          this.name = name;
          this.gender = gender;
          this.job = job;
          this.say = function(person) {
            console.log("sup " + person.name + ", good luck in " + person.job);
          }
        }
        
        var budi = new Test1('Budi', 'male', 'developer');
        var tono = new Test1('Tono', 'male', 'chef');
        
        budi.say(tono);

        【讨论】:

        • 谢谢,没想到我们可以创建新参数T_T
        【解决方案4】:

        你好,请查看这个

        //i change it just for convenient:)
        var People = function(name, gender, job) {
          this.name = name;
          this.gender = gender;
          this.job = job;
          /* you want your `say` function to call another People
          so pass People as the arg, Object with name, gender, job, and another say method*/
          this.say = function(p) {
            /* for string i'd like to use backtick(`) for simplicity and less error phone (ex, space, etc)*/
            console.log(`sup ${p.name}, goodluck in ${p.job}`);
          }
        }
        
        var budi = new People('Budi', 'male', 'developer');
        var tono = new People('Tono', 'male', 'chef');
        
        budi.say(tono);

        【讨论】:

          猜你喜欢
          • 2013-08-09
          • 2017-05-20
          • 1970-01-01
          • 1970-01-01
          • 2018-02-23
          • 2012-05-30
          • 2013-05-28
          • 2013-11-18
          • 1970-01-01
          相关资源
          最近更新 更多