为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)"?

2022-01-24 00:00:00 javascript coffeescript

当我使用最新 (1.0) 版本的咖啡脚本时,一个简单的 javascript 输出看起来像这样(默认情况下):

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);

.call(this) 有什么作用以及添加它的原因是什么?

What does .call(this) do and what would be the reason to add it?

推荐答案

它正在创建一个函数,然后使用父函数/对象范围调用自身.

It's creating a function and then calling itself with the parent function/objects scope.

.call 和 .apply 是调用函数的不同方法.您基本上创建了一个函数,除了在自己的范围内设置 a=1 之外什么都不做.

.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.

在 javascript 中你需要意识到每个函数都是一个对象,而 this 是指当前的对象/函数.使用 .call(this) 覆盖函数内的 this 并将其替换为调用上下文中的那个.

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) overrides this from within the function and replaces it with the one from the calling context.

相关文章