简体   繁体   中英

Concatenate a Javascript function and a string

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!

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM