0

I have a javascript procedural function working with objects belonging to class A:

function max(a, b) {
  if (a > b)
    return a;
  else
    return b;
}
a = max(a, b);

I want to convert it into a method; a try would be:

A.prototype.max = function(b) {
  if (this > b) {
    // do nothing
  } else {
    this = b;
  }
}
a.max(b);

but obviously it doesnt' work, because this can't be assigned.

How can I do?

4
  • 1
    The simple answer is that you can't. Commented Nov 20, 2020 at 8:47
  • Is your goal to make it so after calling a.max(b);, if b is larger, then printing a on the next line will result in the value stored in b? Commented Nov 20, 2020 at 8:59
  • 1
    There's nothing procedural about your function. It doesn't have side effects and instead returns a result like a proper function. Commented Nov 20, 2020 at 9:17
  • Please post the whole code of your "class A" Commented Nov 20, 2020 at 9:18

1 Answer 1

2

I believe the correct thing to do in this case would be to assign the value of a as a property of the class. You could even pass it in on creation:

class A {
  constructor(val = null) {
    this.value = val;
   }

   this.max = function(b) {
     if (this.value > b){
       // do nothing
      } else {
        this.value = b;
      }
   }
}

Replace null with any default value you want, if you don't need to pass it in on creation, or just replace val in the constructor with the default value and take it out as an argument altogether:

class A {
  constructor() {
    this.value = aDefaultValueForAllInstances;
   }
...

Or, with an arrow function, the method would be:

   this.max = (b) => {
     if (this.value > b){
       // do nothing
      } else {
        this.value = b;
      }
   }

You could also simplify the if statement:

if (b < this.value){
  this.value = b;
}

A good sign that you can simplify an if statement is if you aren't doing something in part of it.

If your code is actually this simple then, realistically, you're probably better off just leaving it procedural as it is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.