0

I am trying to concatenate the result returned by a function to a simple string, both are declared inside the same object. Example:

var hello = {
  how: function(){
    return ' are you';
  },
    ans: 'how',
    answer: 'how' + this.how() 
};

console.log(hello.how()); //works
console.log(hello.ans); //works
console.log(hello.answer); //doesnt work

Here is the Fiddle

Thanks for your help!

3
  • answer will need to be a function... Commented Sep 18, 2017 at 19:34
  • See this: stackoverflow.com/questions/16600925/… Commented Sep 18, 2017 at 19:37
  • if you want to use this like you do, than hello has to be an constructor function Commented Sep 18, 2017 at 19:37

2 Answers 2

3

you can use a constructor function to create the object, something like this:

var hello = new function() {
  this.how = function(){
     return ' are you';
  },
  this.ans = 'how',
  this.answer = 'how' + this.how() 
};

console.log(hello.how()); //works
console.log(hello.ans); //works
console.log(hello.answer); //doesnt work

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, both @Nil and your answer work, now my question is, which one is the best approach?
0

This should work:

var hello = {
  how: function(){
    return ' are you';
  },
    ans: 'how',
    answer: function(){
      return 'how' + this.how()
    }
};

console.log(hello.how()); //works
console.log(hello.ans); //works
console.log(hello.answer()); //now works

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.