Search code examples
javascriptfunctionobjectmethodsprototype

How to attach method to method of a function


example:

var A = function (z) {
  this.z = z
}

// attach 1 method

A.prototype.sayHay = function(message) {
  this.message = message
  console.log(message)
}

// attach 2 methods ?????
A.prototype.sayHay.protorype.inReverse = function () {

  // how to avoid the first console.log
  console.log(this.message.split('').reverse().join(''))
}

var b = new A()

b.sayHay('Hola').inReverse()

// this should prints 'aloH'

how can I also override the first console.log, because sayHay prints 'Hi' and would returns inReverse 'iH'

E D I T E D - - - - - - - - - - - - - - - - - - - - - - - - - - -

how can I do, that by executing only sayHay('Hola') I returns 'Hello' and executing sayHay('Hello').inReverse() returns 'aloH' ?


Solution

  • var A = function (z) {
      this.z = z
    }
    
    // attach 1 method
    
    A.prototype.sayHay = function(message) {
      this.message = message;
      return {
        log : function(){console.log(message)},
        rev : function () { console.log(this.message.split('').reverse().join(''))}
      };
    }
    
    var b = new A();
    
    b.sayHay('Hola').rev();
    
    // this should prints 'aloH'
    

    I have tried to do it in way of closures. Check if you get satisfied to achieve your goal with prototype and closure combination.