JS函数问题

var filters = {
  all: function (todos) {
    return todos
  },
  active: function (todos) {
    return todos.filter(function (todo) {
      return !todo.completed
    })
  },
  completed: function (todos) {
    return todos.filter(function (todo) {
      return todo.completed
    })
  }
}

filteredTodos: function () {
  return filters[this.visibility](this.todos)
},

很想问一下filteredTodos这个方法调用filters方法怎么有数组呢?这是什么用法呢?求解惑~

阅读 2.2k
2 个回答

filters[this.visibility] 这里不是数组,是调用对象下的方法。

this.visibility的结果可能有三个 all, active, completed 所以最终是个类似于这样的东西:

filters['all'] 就相当于调用了 filters 对象下的 all 方法,因为 this.visibility 是个变量,所以必须写成这种写法

这几天写了一个前端组件库,gzip之后只有900byte,而且还是零依赖 ( https://github.com/lloydzhou/... ),用这个库实现了一下todo MVC的demo ( https://lloydzhou.github.io/t... )。

我的example里面是这样写的:

    filteredTodos: function (todos, filter) {
        return todos.filter(function (t) {
            return filter == 'all' ? true : filter == 'active' ? !t.completed : t.completed;
        })
    },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题