paula.em.lafon
paula.em.lafon

Reputation: 591

Getting object.function is not a function

I've made a class in javascript called Group which contains some methods. When I try to test those methods the console throws a "x is not a function" I'm not sure of why.

Here's the code

class Group {
  constructor(){
    this.array= []
  }
  add(number){
    this.array.push(number);
  }
  delete(number){
    this.array = filter(this.array, n => n != number);
  }
  has(number){
    for(let value in this.array){
      if(value === number) return true;
    return false;
    }
  }  
  static from(object){
    return this.array = object;
  }
}

Here are the tests

let group = Group.from([10, 20]);
console.log(group);
console.log(group.has(10));
// → true
console.log(group.has(30));
// → false
group.add(10);
group.delete(10);
console.log(group.has(10));
// → false

If the tests aren't passed because my code's not good I don't mind fixing that myself. I'm just wondering why I get the error.

Thank you very much.

Upvotes: 1

Views: 77

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371069

Group.from is a static method - this inside of it will refer to the Group class, not to an instance. So

return this.array = object;

assigns to the class, and returns the passed object itself, which isn't what you want.

Return an instance instead, with new - change the constructor to accept an array which defaults to an empty array, which is assigned to the .array property of the instance:

class Group {
  constructor(arr = []) {
    this.array = arr;
  }
  add(number) {
    this.array.push(number);
  }
  delete(number) {
    // need to define your filter method for this delete method to work
    // this.array = filter(this.array, n => n != number);
  }
  has(number) {
    for (let value in this.array) {
      if (value === number) return true;
    }
    return false;
  }
  static from(arr) {
    return new this(arr);
    // could also do return new Group(arr), but that's less flexible
  }
}

let group = Group.from([10, 20]);
console.log(group);
console.log(group.has(10));
// → true
console.log(group.has(30));
// → false
group.add(10);

Note that your delete method depends on your filter function, which has been left out of the code you posted.

Upvotes: 4

Related Questions