Why is "this.list" Undefined?

Asked

Viewed 38 times

-4

I don’t understand why this.lista is Undefined on line 7, can someone explain to me?

I just want the explanation, I know if I replace, on line 13, .onclick = lista.add for .onclick = function(){ lista.add(); } works.

1 answer

2


this in Javascript is contextual.

When the function add is invoked as a method of an object, as is the case of lista.add, this refers to the object, i.e., this is lista.

When add is invoked within the context onclick of a single element, this refers to the element, i.e., this is botao.

Since you are only passing the function reference to your element, the function is invoked in the element context. this will refer to botao, and botao does not own the property lista, so you get the error não é possível ler a propriedade 'push' de undefined, 'cause when I get the property lista of botao you get undefined, and by invoking push in undefined, you get an error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.