这个值在JavaScript匿名函数中 [英] this value in JavaScript anonymous function

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

问题描述

有人可以向我解释为什么 A 为真且 B 为假?我本以为B也是如此。

Can anybody explain to me why A is true and B is false? I would have expected B to be true as well.

function MyObject() {

};

MyObject.prototype.test = function () {
    console.log("A", this instanceof MyObject);
    (function () {
        console.log("B", this instanceof MyObject);
    }());
}

new MyObject().test();


推荐答案

很特别。它指的是代表函数被调用的对象(最常见的是通过点语法)。

this is special. It refers to the object that the function is being called on behalf of (most commonly via dot syntax).

因此,在 A的情况下,代表新的 MyObject 对象调用该函数。 B 处于一个不代表任何对象显式调用的不同函数中,因此默认为全局对象(窗口)。

So, in the case of A, the function is being called on behalf of a new MyObject object. B is in a different function that isn't explicitly being called on behalf of any object, so this defaults to the global object (window).

换句话说,根据函数的调用方式进行更改,而不是在何处或如何定义。你使用匿名函数(在另一个函数中定义)的事实是巧合的,并且对这个的值没有影响。

In other words, this changes depending on how the function is called, not where or how it is defined. The fact that you're using an anonymous function (defined inside another function) is coincidental and has no effect on the value of this.

这篇关于这个值在JavaScript匿名函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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