Accessing a variable across different scopes in Javascript

こ雲淡風輕ζ 提交于 2020-01-04 09:16:18

问题


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


回答1:


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);
  }
}



回答2:


  1. You can access todos because it is a property of the object you are creating, todoList.
  2. 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.



来源:https://stackoverflow.com/questions/41970294/accessing-a-variable-across-different-scopes-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!