为什么要使用 javascript 函数包装器(在 CoffeeScript 中添加)“.call(this)”?
当我使用最新(1.0)版本的coffee-script时,简单的javascript输出如下所示(默认情况下):
(function() {
var a;
a = 1;
}).call(this);
What does .call(this) do and what would be the Reason to add it ?
When I use the latest (1.0) release of coffee-script, a simple javascript output looks like this (by default):
(function() {
var a;
a = 1;
}).call(this);
What does .call(this) do and what would be the reason to add it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种确保编译后的 CoffeeScript 具有自己的变量名称范围的方法。这在效率和简单性方面都有好处(您知道生成的 JavaScript 不会破坏其他代码使用的变量)。您可以使用 CoffeeScript 编译器的
--bare
(或-b
)选项禁用它。call(this)
的原因只是为了确保 CoffeeScript 与它所在的作用域具有相同的this
,因为函数通常不会继承它们的>this
对象来自周围的上下文。It's a way to make sure that the compiled CoffeeScript has its own scope for variable names. This has benefits in terms of efficiency and simplicity (you know you the generated JavaScript won't stomp on variables used by other code). You can disable it with the
--bare
(or-b
) option to the CoffeeScript compiler.The reason for the
call(this)
is just to ensure that the CoffeeScript has the samethis
as the scope where it's placed, because functions don't normally inherit theirthis
object from the surrounding context.它创建一个函数,然后使用父函数/对象范围调用自身。
.call 和 .apply 是调用函数的不同方法。您基本上创建了一个函数,除了在其自己的范围内设置 a=1 之外,该函数什么都不做。
在 javascript 中,你需要意识到每个函数都是一个对象,而
this
指的是当前对象/函数。使用.call(this)
会覆盖函数内的this
并将其替换为调用上下文中的this
。It's creating a function and then calling itself with the parent function/objects scope.
.call and .apply are different methods of invoking a function. You basically created a function that does nothing except set a=1 within its own scope.
In javascript you need to realize that every function is a object, and
this
is what refers to the current object/function. Using.call(this)
overridesthis
from within the function and replaces it with the one from the calling context.