为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)"? [英] Why use the javascript function wrapper (added in coffeescript) ".call(this)"

查看:10
本文介绍了为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用最新 (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.

这篇关于为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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