M
M
Max Zhukov2018-03-24 21:28:49
JavaScript
Max Zhukov, 2018-03-24 21:28:49

Why doesn't the class method see the element through this?

How to make sum([1,2,3],1,2) work?
Swears that cash is not defined.

class Sum {
  constructor (){
    this.cash = {};
  }
    sum(arr, start, end) {
        var result = 0,
            key = arr.toString() + start + end;
        if (key in this.cash) {
            return this.cash[key];
        }
        for (let i = start - 1; i < end; i++) {
            result += arr[i];
        }
        this.cash[key] = result;
        return result;
    }
}
var sum = new Sum().sum;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-03-24
@MaksZhukov

Since the reference to the sum function is stored in the sum variable and then the call is made through the variable, this does not point to Sum ( https ://developer.mozilla.org/en/docs/Web/JavaScri... in this case, bind the sum method to the Sum object by adding this.sum = this.sum.bind(this);

class Sum {
  constructor (){
    this.cash = {};
    this.sum = this.sum.bind(this);
  }
    sum(arr, start, end) {
        var result = 0,
            key = arr.toString() + start + end;
        if (key in this.cash) {
            return this.cash[key];
        }
        for (let i = start - 1; i < end; i++) {
            result += arr[i];
        }
        this.cash[key] = result;
        return result;
    }
}
var sum = new Sum().sum;
sum([1,2,3],1,2);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question