我正在学习 JavaScript,为了提高我对语言的了解,我一直在尝试了解这个待办事项列表应用程序的工作原理。源代码可在此处获得。
总的来说,我觉得我对代码的理解相当好。只有一件事困扰着我:在第 43 行,在“App”对象的“init”方法中,发生了以下情况:
this.todos = util.store('todos-jquery');
为了给你上下文,这里是“App”对象和“init”方法的开始:
var App = {
init: function () {
this.todos = util.store('todos-jquery'); // <= this line
this.todoTemplate = Handlebars.compile($('#todo-template').html());
this.footerTemplate = Handlebars.compile($('#footer-template').html());
this.bindEvents();
...
},
...
}
我不明白的是,你为什么要通过在“init”方法中使用“this.todos”来定义“todos”,而不是像我下面那样将它直接放入“App”对象中:
var App = {
todos: util.store('todos-jquery'), // <= this line
init: function () {
this.todoTemplate = Handlebars.compile($('#todo-template').html());
this.footerTemplate = Handlebars.compile($('#footer-template').html());
this.bindEvents();
...
}
...
}
我一直在阅读 MDN 网络文档和其他文章(例如这篇文章)中的“this”关键字,试图自己回答这个问题,但不知何故,我觉得没有一个例子真正符合我上面描述的情况。
所以我得到了源代码并尝试查看在进行上述更改后应用程序是否仍然有效。它确实如此。我现在假设这两种方法是等效的:使用一种方法而不是另一种方法有什么好处吗?还是仅取决于每个开发人员的编程风格?
拉莫斯之舞
相关分类