Whether you are a seasoned engineer or new to coding, 1 common error you are likely to come across alot is 'Cannot read the value undefined of this'
It is a very confusing concept that puts many people off, so I'll be trying to explain concisely what this is
Take the following for example
function getLetters(a, b) {
let obj = {firstLetter: a, secondLetter: b}
return (this.obj)
}
let display = getLetters(a, b)
We would expect display to equals to {a, b} right?
well no, what you would get is undefined
Lets see another example
let shoppingList = {
fruits: 'banana',
cake: 'chocolate'
}
let getItems= function() {
console.log(this.fruits + '' + this.cake)
}
let result = getItems(fruits, cake);
javascript
We would expect results to equal 'banana chocolate' right?
Nope what you get is an error
So what exactly is wrong? Well this is not what you think this is, one might think in the first example that this would refer to the obj and the fruit and cake keys in the second example but it does not
This actually gets its value at the function invocation, meaning the binding of a value happens when you invoke the function, and the object to the left of the invocation is what gets binded to the value of this
Illustration
let wishlist = {games: 'Xbox Scarlett'}
let viewWishlist = function (games) {
return this.games;
}
let result = wishList.viewWishList('PS5')
javascript
In this scenario, what will we expect the value of result to be? Well if you guessed 'Xbox Scarlett' you are absolutely right, the value of this was binded to the object that was invoked with the function, but you might ask, hey Williams, what if we don't call the function with a value to the left of the dot, what then becomes the value of this? Good question
The value of this in this situation will the global object, why? Because our rule still applies, what is to the left of the function invocation viewWishlist()? You can't see it but the function is actually being invoked with global object. Which is why the values of this is being binded to the global object
Now that that's out of the way, you might be wondering, hey Williams, what if I want to tell my function the object I want to be binded with the value of this, well you call the function with a call or apply function and pass the value you want to be binded to this as the first argument
viewWishList.call(objToBind, args)
So here the value of this is going to be binded to the object objToBind.
I hope with my illustrations I've been able to explain to you what this means and how to use it in your codes :)
Top comments (0)