var todoList = {
todos: []
displayTodos: function () {
console.log(this.todos[i].todoText);
}
addTodo: function (todoText) {
this.todos.push({todoText: todoText});
}
}
This isn't the complete program, but my question is this:
In the displayTodos function, how am I able to access todoText (in the console log line)?
Shouldn't the todoText variable that's declared in the addToDo function be limited in scope to the function in which it's declared, addToDo?
Thanks
Technically, neither of the things you asked about is a variable. They are both properties of different objects that you are creating with the object literal syntax.
This has to do with the *context * of a function. Not scope, but context.
Scope:
This relates to what variables are visible to a function.
Functions have access to their local variables (declared inside the body of their definitions including any argument parameters which get added as local variables) and any variables in the enclosing scope that they are called.
Context (applies to OP question):
Has to do with how the function was called or what object it gets assigned to at the time it is called/invoked. More specifically, it defines what the value of
this
resolves to in a function definition.An example
Let's make the assumption that you are calling these methods as follows:
In the case above all three functions are called as methods of the object
todoList
and in turn, thethis
value inside of both will refer to thetodoList
object.After pushing an object that contains a property
todoText
intothis.todos
array you'll have the following array:And you can access each stay element by pushing in the correct index to
displayTodo
(albeit with a slight modification to your code to accept the index as an argument)