_.each(list, iterator, [context]) 中的上下文是什么? [英] What is context in _.each(list, iterator, [context])?

查看:31
本文介绍了_.each(list, iterator, [context]) 中的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 underscore.js 的新手._.each()[context] 的目的是什么?应该如何使用?

I am new to underscore.js. What is the purpose of [context] in _.each()? How should it be used?

推荐答案

context参数只是设置迭代器函数中this的值.

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

工作示例: http://jsfiddle.net/a6Rx4/

它使用来自正在迭代的 Array 的每个成员的数字来获取 someOtherArray 索引处的项目,它由 this 表示,因为我们将它作为上下文参数.

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

如果不设置上下文,那么this将引用window对象.

If you do not set the context, then this will refer to the window object.

这篇关于_.each(list, iterator, [context]) 中的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆