匿名函数的上下文是什么? [英] What is the context of an anonymous function?

查看:37
本文介绍了匿名函数的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

function demo() {
    this.val=5;
    function() {
        this.val=7;
    }();
}

现在,当我在 firefox 或 chrome 控制台中执行此代码时,它会出现语法错误.我不明白为什么这是一个错误,因为我已经读过 javascript 函数是对象,所以当我调用匿名函数时,在它里面 this 指向函数 demo 并且应该更改 val7,所以如果我这样做

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;
}();

被评估为函数声明,函数声明需要一个名称.为了让它被解释为函数表达式,你需要把它放在括号里:

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;
 }());

(使其成为立即函数)

或将函数赋值给一个变量:

or assign the function to a variable:

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.

i dont understand if functions are objects then why the this in the anonymous function points to window and not demo.

函数不继承调用它们的上下文.每个函数都有自己的thisthis 引用什么由how 函数被调用.它基本上归结为:

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

应用 [docs]call[docs] 方法( func.apply(someObj) ):this 指的是 someObj

apply [docs] and call [docs] methods ( func.apply(someObj) ): this refers to someObj

进一步阅读:

这篇关于匿名函数的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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