javascript在对象中传递参数

时间:2016-11-15 11:11:41

标签: javascript object arguments

对不起,即使看了很多视频并且在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');

我想通过argument传递object

budi.say(tono);

4 个答案:

答案 0 :(得分:1)

您可以实现say()

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

或称之为:

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

答案 1 :(得分:1)

您可能想要改为

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

如果为不同的范围指定相同的名称参数,它们将被视为不同的变量。你可以这样做:

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

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

答案 2 :(得分:0)

say()方法中,从方法参数(我的示例中为name)中读取jobperson



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




答案 3 :(得分:0)

嗨,请查看这个



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