Eliseo
Eliseo

Reputation: 712

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' ?

Upvotes: 0

Views: 547

Answers (3)

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.

Upvotes: 1

Renato Gama
Renato Gama

Reputation: 16519

Here is another way using regular classes

class Sayer {
  constructor (message) {
    this.message = message
  }
  
  inReverse() {
    return this.message.split('').reverse().join('')
  }
  
  toString() {
    return this.message   
  }
}

class A {
  sayHay(message) {
     return new Sayer(message)
  }
}

console.log(new A().sayHay('Hola').inReverse())
console.log(new A().sayHay('Hola').toString())

Upvotes: 0

Ele
Ele

Reputation: 33726

A prototype is used in situations where you create an object using the keyword new.

For Example:

new A().sayHay(...).[Any method from the prototype]

So, you can initialize the variable b and then execute the function sayHay as a constructor:

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

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

// attach 1 method
A.prototype.sayHay = function(message) {
  this.message = message
  //console.log(message);
}

A.prototype.sayHay.prototype.inReverse = function () {
  // how to avoid the first console.log
  console.log(this.message.split('').reverse().join(''))
}

var b = new A();
new b.sayHay('Hola').inReverse();

To avoid the first console.log(message) you can replace that function at runtime, or remove that line.

Another alternatives is avoiding the second prototyping and return an object:

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

// attach 1 method
A.prototype.sayHay = function(message) {
  return {
    message: message,
    inReverse: function() {
      console.log(this.message.split('').reverse().join(''));
    }
  }
}

var b = new A();
b.sayHay('Hola').inReverse();

Upvotes: 0

Related Questions