Search code examples
javascriptobject-literal

Object literal and method grouping


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)


Solution

  • 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