将javascript参数从对象构造函数传递给对象的方法?

时间:2014-05-26 22:08:34

标签: javascript object methods parameter-passing

在设置构造函数时,是否有可能将其参数传递给其中一个方法?这就是我的意思:

function jedi(name,text){
    this.name = name;
    this.quote = function quote(name,text){
         return name + " said " + text;
    };
}

 var obiwan = new jedi('Obi-Wan','Fear leads to the darkside');
 console.log(obiwan.quote());  //renders as undefined said undefined

 //this works fine though
 console.log(obiwan.quote('Obi-Wan','Fear leads to the darkside'));

是否可以将'name'和'text'参数直接从'var obiwan = new jedi()'传递给'obiwan.quote()'? 我希望我的问题有道理。在此先感谢任何可以帮助我的人!

2 个答案:

答案 0 :(得分:1)

只需使用实例变量吗?

function jedi(name,text){
    this.name = name;
    this.text = text;

    this.quote = function quote(){
         return this.name + " said " + this.text;
    };
}

 var obiwan = new jedi('Obi-Wan','Fear leads to the darkside');
 console.log(obiwan.quote());  //works like a charm

答案 1 :(得分:0)

quote函数的参数赋予不同的名称,而不是给予构造函数参数的名称。

function jedi(name,text){
    this.name = name;
    this.quote = function quote(_name,_text){
         return (_name || name)  + " said " + (_text || text);
    };
}

var obiwan = new jedi('Obi-Wan','Fear leads to the darkside');

console.log(obiwan.quote());  
// would rendera as Obi-Wan said Fear leads to the darkside

console.log(obiwan.quote('I', "is the new X-men inspired from Assassin's Creed?"));
// would rendera as I said is the new X-men inspired from Assassin's Creed?