0

I have an array of objects, all of them with the same properties, but one of those properties should be a function, that decides if the object is “visible” or not

Something like:

let ObjArr = [{
  name: 'Charles',
  age: 30,
  visible: (aName, anAge) => {
    return (((this.name === aName) && (this.age === anAge)) ? true : false)
  }
}]

console.log(ObjArr[0].visible('Charles', 30)) // It should be true
console.log(ObjArr[0].visible('Peter', 30)) // It should be false
console.log(ObjArr[0].visible('Charles', 25)) // It should be false too

Currently, all of them say false, but the first should be true

Thanks in advance

Rafael

evolutionxbox
  • 2,659
  • 4
  • 31
  • 41
Rafael
  • 1,333
  • 3
  • 18
  • 37

2 Answers2

1

With fat-arrow functions (i.e. =>), the this reference is "lexical". It means that the this reference points to whatever this was when objArr was defined. Whatever that object is, it probably doesn't have the name or age properties, which means that this.name is undefined, and so is this.age, so your comparisons both yield false.

To make the function take this reference from whatever object it was called "from" (or "on"), declare it using the function keyword:

let ObjArr = [{
  name: 'Charles',
  age: 30,
  visible: function(aName, anAge) {
    return (((this.name === aName) && (this.age === anAge)) ? true : false)
  }
}]

console.log(ObjArr[0].visible('Charles', 30)) // It should be true
console.log(ObjArr[0].visible('Peter', 30)) // It should be false
console.log(ObjArr[0].visible('Charles', 25)) // It should be false too

Alternatively, you can use the "method" syntax:

let ObjArr = [{
  name: 'Charles',
  age: 30,
  visible(aName, anAge) {
    return (((this.name === aName) && (this.age === anAge)) ? true : false)
  }
}]

It will have the same effect.


Bonus pointer: if you have a boolean value x, then expression x ? true : false is equivalent to just x. This means that your function could be:

  function(aName, anAge) {
    return (this.name === aName) && (this.age === anAge)
  }
Fyodor Soikin
  • 67,206
  • 8
  • 106
  • 148
1

You cannot use an arrow function if you want to use the this reference; however, you can use a method definition shorthand.

let ObjArr = [{
  name: 'Charles',
  age: 30,
  visible(aName, anAge){
    return (((this.name === aName) && (this.age === anAge)) ? true : false)
  }
}]

console.log(ObjArr[0].visible('Charles', 30)) // It should be true
console.log(ObjArr[0].visible('Peter', 30)) // It should be false
console.log(ObjArr[0].visible('Charles', 25)) // It should be false too
iota
  • 34,586
  • 7
  • 32
  • 51