匿名函数的上下文是什么? [英] What is the context of an anonymous function?
问题描述
我有这样的代码:
function demo() {
this.val=5;
function() {
this.val=7;
}();
}
现在,当我在firefox或chrome控制台中执行此代码时,会出现语法错误.我不明白为什么会出错,因为我已经了解到javascript函数是对象,因此当我调用匿名函数时,其中的this
指向函数demo,应将val
更改为7
,所以如果我有
Now when I give execute this code in the firefox or chrome console it gives a syntax error. I don't understand why this is an error because I have read that javascript functions are objects so when I call the anonymous function, inside it this
points to function demo and should change the val
to 7
, so if I do
var x=new demo();
x.val; //should give 7
但是当我这样做
function demo() {
this.val=5;
var f=function() {
this.val=7;
}();
}
window.val; // gives 7
我不明白函数是否是对象,为什么匿名函数中的this
指向window
而不是demo
.
请解释一下.
I don't understand if functions are objects then why the this
in the anonymous function points to window
and not demo
.
Please explain this.
推荐答案
我不明白为什么这是一个错误
i dont understand why this is an error
因为
function() {
this.val=7;
}();
被评估为函数声明,并且函数声明需要一个名称.要将其解释为函数 expression ,您需要将其放在括号中:
is evaluated as function declaration and function declarations need a name. To make it interpreted as function expression, you need to put it in parenthesis:
(function() {
this.val=7;
}());
(使其立即生效)
或将函数分配给变量:
var f = function() {....};
f();
第二个片段中的操作是两者的混合,虽然有效,但意义不大. f
将具有值undefined
.
What you do in the second snippet is a mixture of both and although being valid, it does not make much sense. f
will have the value undefined
.
我不明白函数是否是对象,那么为什么匿名函数中的this指向
window
而不是demo
.
函数不会继承调用它们的上下文.每个函数都有它自己的this
,而this
所指的是由如何确定的.基本上可以归结为:
Functions don't inherit the context they are called in. Every function has it's own this
and what this
refers to is determined by how the function is called. It basically boils down to:
-
独立"(
func()
)或作为立即函数((function(){...}())
):this
将引用全局对象(在浏览器中为window
)
"Standalone" (
func()
) or as immediate function ((function(){...}())
) :this
will refer to the global object (window
in browsers)
作为对象的属性(obj.func()
):this
将引用obj
As property of an object ( obj.func()
): this
will refer to obj
使用 new
[docs] 关键字(new Func()
):this
表示从Func.prototype
With the new
[docs] keyword ( new Func()
): this
refers to an empty object that inherits from Func.prototype
apply
[docs] 和 call
[docs] 方法(func.apply(someObj)
):this
指的是someObj
apply
[docs] and call
[docs] methods ( func.apply(someObj)
): this
refers to someObj
进一步阅读:
- MDC JavaScript Guide - Functions
- MDC JavaScript Reference - Function and functions scope
- ECMAScript 5, Section 13 - Function Definition
这篇关于匿名函数的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!