的javascript传递参数的对象
问题描述:
对不起,我这样的新手甚至不完全了解,即使经过观看大量视频和寻找在计算器这么难,甚至无法正常找到我的问题(与不同的对象传递的参数?)所以我在这里只会显示我的代码。的javascript传递参数的对象
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);
答
你可以任选的say()
this.say = function(person){
console.log(" sup "+ person.name +", goodluck in" + person.job);
}
这或实行调用它喜欢:
budi.say(tono.name, null, tono.job)
答
在say()
方法读取所述方法参数的name
和job
( 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);
答
你可能想要做的,而不是
this.say = function(/*no arguments here*/){
console.log(" sup "+ this.name +", goodluck in" + this.job);
}
如果你把同一个名字参数不同的范围,它们将被视为不同的变量。这样你可以这样做:
var budi = new Test1('Budi', 'male', 'developer');
budi.say();
,它会正确地显示你在构造函数中使用的字符串。
答
喜请查看这个
//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);
感谢,didnt甚至认为我们可以创造新的参数T_T –
不客气:)祝你好运与您的研究。 –