Question on Setters

Question on Setters
0

#1

A question on a test I took: Is there anything wrong with setter method in the example below? If so, what?

let tempObj = {
_num: 22,
set num(numIn) {
_num = numIn;
}
};

Answer:

let tempObj = {
_num: 22,
set num(numIn) {
this._num = numIn;
}
};

Why do I have to use this._numIn?

Wouldn’t it know _num because of scope?


#2

When in doubt, I write code to test it, like in this pen.

let tempObj1 = {
  _num: 22,
  set num(numIn) {
    console.log('tempObj1 this = ', this)
    console.log('tempObj1 this._num = ', this)
    this._num = numIn
  },
  get num() {
    return this._num
  }
}

let tempObj2 = {
  _num: 22,
  set num(numIn) {
    console.log('tempObj2 this = ', this)
    console.log('tempObj2 _num = ', _num)
    _num = numIn
  },
  get num() {
    return _num
  }
}

tempObj1.num = 123
console.log('final tempObj1.num =', tempObj1.num)
tempObj2.num = 456
console.log('final tempObj2.num =', tempObj2.num)

It fails on the second one, “Uncaught ReferenceError: _num is not defined”.

This is because this can be kind of squirrelly and works a little differently on object methods. From MDN, “When a function is called as a method of an object, its this is set to the object the method is called on.

So, this in this case is not the scope, but the object itself - it is how you refer to properties on the object. If you just refer to _num, it looks in the current scope and cannot find a variable with that name. In theory you could have a variable (a global for example) with that name and it would refer to that. To make sure you are talking about the property on that object, you must use this.


#3

Thank you so much. I see what I was getting mixed up on now!