Why use the javascript function wrapper (added in coffeescript) quot;.call(this)quot;(为什么要使用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)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)"?
基础教程推荐
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01