Javascript 下划线.js - 我必须使用上下文参数和“this”吗?
Javascript underscore.js- do I have to use a context parameter and 'this'?
在我正在观看的教程中,下划线此代码用于演示_.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
并且必须在上下文中传递?
就像评论中提到的,这不是必需的,但在某些情况下可能很有用。它还使迭代器函数不知道上述范围。它只知道它正在处理具有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);
相关文章:
- 将$(this)作为参数发送
- 将对象this发送到不带参数的函数
- 在新对象参数中使用“this”选择器
- 如何将“$(this)”作为参数传递给Javascript中的“callready”函数
- 传递和接收 $(this) 作为参数的方法
- jQuery 将$this传递给函数参数
- Javascript 窗口函数将“this”作为参数传递
- 带参数的“this”函数
- 使用bind(this)并一起传递参数
- 当用作函数参数/agrument时,关键字this指的是什么
- this.location未传递json参数
- this.apply 方法,以此作为参数
- 传递一个原型's函数作为参数而不丢失'this'上下文
- 我怎么会有'this'setTimeout参数中的关键字
- 将' this '参数发送给函数
- JavaScript -使用apply来调用函数,但是'this'未被设置为作为第一个参数传递的对象
- JQuery $(this)不能在函数参数中工作
- javascript函数参数异常行为** WHAT's THIS
- 如果我没有在回调中使用' this '关键字,我应该使用可选的context参数吗?
- Javascript send "this"对象作为参数