Home > Mobile >  Reimplement function in terms of existing function
Reimplement function in terms of existing function

Time:11-03

Let's suppose I have this simple code:

const a = {
  number: 2,
  method() {
    return this.number
  }
}


console.log(a.method()) // prints 2

Now I'd like to reimplement method in terms of method itself. Ideally:

a.method = function() {
   return 40   this.method() // should print 42, get a RangeError: Maximum call stack size exceeded
}

Is there a way to achieve this?

CodePudding user response:

You could try something like this:

const a = {
  number: 2,
  method() {
    return this.number
  }
}

// 1. Store old method
var oldMethod = a.method.bind(a)

// 2. Reference old method in new declaration
a.method = function() {
  return 40   oldMethod()
}

console.log(a.method())

See MDN for more info on .bind.

  • Related