在 JavaScript 中的对象方法中使用 'this'

Using 'this' in objects methods in JavaScript

我正在学习 JavaScript 并且为了提高我的语言知识,我一直在努力理解 todo-list application works. The source code is available here

总的来说,我感觉我对代码的理解还算不错。只有一件事困扰着我:在第 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',而不是直接将其放入 [=30] =] 对象,如下所示:

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 one 等其他文章中的 'this' 关键字,试图自己回答这个问题,但不知何故我觉得 none 的例子确实符合我上面描述的情况。

所以我得到了源代码并尝试查看应用程序在进行上述更改后是否仍然有效。确实如此。我现在假设这两种方法是等价的:使用一种方法比使用另一种方法有什么好处吗?还是仅仅取决于每个开发人员的编程风格?

一般来说当你有:

var X = {
  y: z(),
  init: function() {
  }
};

这应该等同于:

var X = {
  init: function() {
    this.y = z();
  }
}

前提是您调用 X.init() 并且确信在此之前调用 z() 没有问题。最终结果是 X.y 填充了 z().

的 return 值

第二种方法,所有内容都在 init() 中,使您可以更好地控制排序,从一致性和简单性的角度来看可能更可取。在这种特殊情况下,它似乎是任意的。

在现代 JavaScript 你真的应该有:

class X {
  constructor() {
  }

  y = z();
}

在那里你可以依次调用 let x = new X()x.y()