1

Is it possible, while setting up a constructor, to have it's parameters passed right into one of it's methods? Here's what i mean:

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

Is it possible to pass the 'name' and 'text' parameters right from 'var obiwan = new jedi()' to 'obiwan.quote()'? I hope my question makes sense. Thanks in advance to anyone that can help me out!

1

2 Answers 2

1

Just use the instance variables?

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
Sign up to request clarification or add additional context in comments.

1 Comment

OMG thank you. I knew i was missing something silly right in front of my face! Thank you Jari
0

Give a different name to the parameters of quote function, than those given to the constructor parameters.

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.