在 JavaScript 的 Underscore.js 库中,“上下文”的作用是什么?是什么意思以及如何使用它?
我正在阅读 Underscore.js 库的文档www.documentcloud.org/home" rel="noreferrer">DocumentCloud。许多函数都采用可选的上下文参数,但未对此进行解释。我的猜测是,熟悉 Ruby 的人认为这类似于 Ruby 绑定
。它与 this
的含义有关。我的 JavaScript 使用范围是一些 jQuery 调用和一些非常样板的 ajax。
我的问题:context
是什么意思以及我应该如何使用它?一个好的答案可能还应该包含一些有关 JavaScript 如何工作的信息。
I'm reading the documentation for the Underscore.js library from DocumentCloud. Many of the functions take an optional context
argument which is not explained. My guess, as one familiar with Ruby is that this is similar to a Ruby binding
. And that it has something to do with what this
means. The extent of my JavaScript usage has been a few jQuery calls and some very boilerplate ajax.
My question: What does context
mean and how should I use it? A good answer should probably contain some information about how JavaScript works as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Javascript 函数采用一个隐藏的
this
参数,该参数指示调用该函数的上下文。通常,
this
是全局对象(通常是window
)。但是,当对对象调用函数时,this
将是调用它的对象。采用回调函数的 Underscore.js 方法采用可选的
context
参数。如果指定了此参数,则将使用该上下文
调用回调,这意味着回调中的this
将等于上下文。Javascript functions take a hidden
this
parameter which indicates the context in which the function was called.Ordinarily,
this
is the global object (usuallywindow
). However, when a function is called on an object,this
will be the object that it was called on.Underscore.js methods that take callback functions take an optional
context
parameter. If this parameter is specified, the callback will be called with thatcontext
, meaning thatthis
inside the callback will be equal to the context.