When a new function is defined without binding this
, it can lead to unexpected behavior as the function will have its own this
which may clash with the intended class.
To avoid this issue, arrow functions should not be used as they do not have an internal this
pointer.
If you need to use this
inside processPerson, you can do so by running:
return processPerson.bind(this)
Alternatively, you could store the value of this
in another variable name. However, this method is considered less optimal for inheriting properties and can be achieved through deep copying with Object.assign or similar methods.
The final code snippet may look like this:
interface Person { name: string; age: number }
class TestClass {
get person(): Person | undefined {
if (Math.random() > 0.5) return undefined
return { name: 'Bob', age: 35 }
}
get test() {
if (!this.person) return undefined
const name = this.person.name // No error
const processPerson = (function() {
return this.person.name;
}).bind(this);
return processPerson()
}
}
This guard check:
if (!this.person) return undefined
ensures that
this.person
is not undefined when the returned function is created. However, it does not guarantee that
this.person
will have a value when the function is called, leading to potential undefined behavior. For consistent and encapsulated behavior, it is advisable to bind
this
.