Object literal and method grouping

62 Views Asked by At

Could someone tell me how to write the below in an "object-literal" fashion..

my.item('apple').suffix("is awesome")
// console.log >> apple is awesome

My attempt ... but it obviously doesn't work.

var my = {
    item:function(item){
        my.item.suffix = function(suffix){
            console.log(item, suffix);
        }
    }
};

(Sorry if the title is wrong. I'm not sure of the terminology)

1

There are 1 best solutions below

6
On BEST ANSWER

Try this:

var my = {
  thing: undefined,

  // sets the `thing` property of `my`,
  // then returns `my` for chaining
  item: function (t) {
    thing = t;
    return this;
  },

  // concatenates the `thing` property with the given
  // suffix and returns it as a string
  suffix: function (s) {
    return thing + ' ' + s;
  }
};

my.item('apple').suffix("is awesome");
//--> apple is awesome