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
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:
todoList.addTodo("some text");
todoList.addTodo("other text");
todoList.dispayTodo(1); // made this singular, see below for explanation
// logs out > "other text"
In the case above all three functions are called as methods of the object todoList
and in turn, the this
value inside of both will refer to the todoList
object.
After pushing an object that contains a property todoText
into this.todos
array you'll have the following array:
[
{todosText:"some text"},
{todosText:"other text"}
]
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)
var todoList = {
...
displayTodo: function(i) {
console.log(this.todos[i].todoText);
}
}
- You can access todos because it is a property of the object you are creating, todoList.
- todoText is not a variable, it's a property name for a new object you are creating and pushing to todos. Thus it can be used in any scope that has access to todos.
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.