为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this) [英] Why use the javascript function wrapper (added in coffeescript) ".call(this)"
问题描述
当我使用最新的(1.0)版本的咖啡脚本时,一个简单的javascript输出看起来像这样(默认情况下):
(function(){
var a;
a = 1;
})。
.call(this)会做什么添加它?
它创建一个函数,然后用父函数/ objects范围调用。
.call和.apply是调用函数的不同方法。
在javascript中,你需要意识到每个函数都是一个对象,而 this
是指当前对象/函数。在函数中使用 .call(this)
覆盖这个
,并用调用上下文中的一个替换。 / p>
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?
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)
overrides this
from within the function and replaces it with the one from the calling context.
这篇关于为什么要使用javascript函数包装器(在coffeescript中添加)“.call(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!