匿名函数的上下文是什么?
我有这样的代码:
function demo() {
this.val=5;
function() {
this.val=7;
}();
}
现在,当我在 Firefox 或 Chrome 控制台中执行此代码时,它会出现语法错误。我不明白为什么这是一个错误,因为我已经读到 javascript 函数是对象,因此当我调用匿名函数时,其中的 this
指向函数 demo 并且应该更改 val< /code> 到
7
,所以如果我这样做
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
指向 窗口
而不是演示
。 请解释一下。
I have code like this:
function demo() {
this.val=5;
function() {
this.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
but when I do this
function demo() {
this.val=5;
var f=function() {
this.val=7;
}();
}
window.val; // gives 7
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
,因为
被评估为函数声明并且函数声明需要一个名称。要使其解释为函数表达式,您需要将其放在括号中:(
使其成为立即函数)
或将函数分配给变量:
您在第二个片段中所做的事情是两者的混合虽然有效,但没有多大意义。
f
的值为undefined
。函数不会继承调用它们的上下文。每个函数都有自己的
this
,而this
所指的内容取决于该函数的方式被称为。它基本上可以归结为:“独立”(
func()
)或作为立即函数((function(){...}())
):this
将引用全局对象(浏览器中的window
)作为对象的属性 (
obj.func()
):this
将引用obj
使用
new
[docs] 关键字 (new Func()
):this
指的是一个空对象,继承自Func.prototype
应用
< em>[文档] 和 <代码>调用 [docs] 方法(func.apply(someObj)
):this
引用someObj
进一步阅读:
because
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:
(making it an immediate function)
or assign the function to a variable:
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 valueundefined
.Functions don't inherit the context they are called in. Every function has it's own
this
and whatthis
refers to is determined by how the function is called. It basically boils down to:"Standalone" (
func()
) or as immediate function ((function(){...}())
) :this
will refer to the global object (window
in browsers)As property of an object (
obj.func()
):this
will refer toobj
With the
new
[docs] keyword (new Func()
):this
refers to an empty object that inherits fromFunc.prototype
apply
[docs] andcall
[docs] methods (func.apply(someObj)
):this
refers tosomeObj
Further reading:
您可以像这样执行您所描述的操作:
You can do what you described like this: