var a = bc = function(){} 语法的用途
我最近浏览了 js 代码,不断出现以下语法:
var foo = bar.bi = function() {...}
这对我来说是陌生的语法。难道只是为同一个函数定义两个名字吗?如果是这样,为什么不只将其定义为 bar.bi = function()
呢?
I've lately browsed js code and the following syntax keeps coming up:
var foo = bar.bi = function() {...}
This is unfamiliar syntax to me. Is it only to define two names for the same function? If so, why not only define it as bar.bi = function()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
同时为变量和
bar
对象的bi
属性分配相同的值。通过这种方式,对象的属性可以获得值,但您仍然可以将其作为变量引用,这可能会更快一些。
实际上与...相同,
或者您可以将其想象为...
因此首先发生对
bar.bi
的赋值。从赋值表达式返回的结果是相同的函数,并且该结果被赋值给foo
。Assigns the same value to the variable and the
bi
property of thebar
object at the same time.This way the object's property gets the value, but you can still reference it as a variable, which is likely a little faster.
Effectively the same as...
Or you can visualize it as...
So the assignment to
bar.bi
happens first. The result returned from the assignment expression is the same function, and that result is assigned tofoo
.除了将函数分配给 2 个变量之外,上下文也会根据您调用它的方式而变化。
会将其上下文作为
bar
对象,就好像您会使用它一样:但在另一个变量中使用它,如下所示:
将使用
foo
的上下文。因此,如果 foo 位于全局上下文中,它将相当于:In addition to assigning the function to 2 variable, the context also changes depending on how you call it.
would have it's context as the
bar
object, as if you would have used this:But using it off the other variable, like this:
would use the context of
foo
. So iffoo
is in the global context, it'll be equivalent to this:这只是一个复合赋值,
将 3 赋给 x,也赋给新声明的 r。
您的示例只是用一个函数代替 3,用一个对象属性 -
bar.bi
- 代替x
。It's just a compound assignment
assigns 3 to x, and also to r, which is newly declared.
Your example just substitutes a function in place of 3, and an object property—
bar.bi
—in place ofx
.这取决于它的使用地点。
foo
和bar.bi
都指向相同的函数。 调用该函数这意味着可以使用and
,同时函数内部
this
的值有所不同。要使第一个等于第二个,应按如下所示调用它或
这可确保
this
将指向函数内的bar
。请参考:
https://developer.mozilla.org/en/JavaScript/参考/Global_Objects/函数/调用。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /函数/应用。
。
It depends on where it is used.
Both
foo
andbar.bi
point to same function here. That means the function can be invoked usingand
At the same time it differs in the value of
this
inside the function. To make the first one equal to second one, it should be invoked as given belowor
This ensures that
this
will point tobar
inside the function.please refer:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply.
.
bar 将是一个响应方法 bi 的对象。
bar will be an object who responds to method bi.