【问题标题】:Javascript underscore.js- do I have to use a context parameter and 'this'?Javascript underscore.js-我必须使用上下文参数和“this”吗?
【发布时间】:2015-06-20 09:14:01
【问题描述】:

在我正在观看的下划线教程中,此代码用于演示_.each

var people = {
    names: ['Craig', 'John', 'Dan', 'Elijah'],
    getMessage: function(name) {
      return 'Hello there, ' + name + '!';
    }
};

_.each(people.names, function(element, index, list) {
  console.log(this.getMessage(element))
}, people);

据解释,people 作为_.each 调用的上下文传递,以将this 绑定到people 对象,但我不明白为什么这是必要的。我不能在迭代器函数的主体中明确写出people.getMessage 吗?

喜欢:

_.each(people.names, function(element, index, list) {
  console.log(people.getMessage(element));
});

为什么要使用this 并且必须传入上下文?

【问题讨论】:

  • 因为这样函数可以泛化为应用于任何对象而不是一个特定对象。
  • 为什么需要这样做这是不必要的,但非常有用
  • “上下文”在 javascript 中是一个被滥用的术语。将短语“as context for”替换为单词“to”,也许它更有意义。说“people 被分配给函数的 this”也更正确,因为这就是发生的事情。

标签: javascript underscore.js this


【解决方案1】:

就像在 cmets 中提到的那样,这不是必需的,但在某些情况下它可能很有用。它还使迭代器函数不知道上述范围。它只知道它正在处理具有getMessage() 方法且未链接到闭包中的特定变量的对象。

我能想到的一个例子是能够为具有相同结构但在范围内未命名为 people 的不同对象重用它。

var people = {
    names: ['Craig', 'John', 'Dan', 'Elijah'],
    getMessage: function(name) {
      return 'Hello there, ' + name + '!';
    }
};

var dogs = {
  names: ['Jimmy', 'Rufus', 'Woofie', 'Silly'],
  getMessage: function(name) {
      return 'Woof there, ' + name + '!';
    }
};

function logTheMessage(element) {
  console.log(this.getMessage(element));
}

_.each(people.names, logTheMessage, people);
_.each(people.names, logTheMessage, dogs);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多