Javascript这个关键字 - 内部功能 [英] Javascript this keyword - inside function

查看:72
本文介绍了Javascript这个关键字 - 内部功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 Javascript 上的关键字。

I am trying to understand the this keyword on Javascript.

I我正在对Chrome控制台进行一些测试,我遇到了两个不同的结果,我期望它们是相同的:

I was doing some tests on chrome console and I came across two different results that I was expecting to be the same:

var myTest = {};
myTest.test1 = function() {
        return this; // this = Object
}

第一个函数返回 myTest 我理解的对象。

This first function returns myTest object which I understand.

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        return this; // this = Window
    }
}

为什么第二个函数返回窗口而不是 myTest 对象?

Why is the second function returning the window instead of the myTest object?

谢谢

推荐答案

指的是调用该函数的当前对象。当您调用 test1 时,您可能会这样做

this refers to the current object on which the function is called. When you called test1, you would have done like this

myTest.test1()

现在,调用 test1 myTest 对象上。这就是这个在第一种情况下引用 myTest 的原因。

Now, test1 is called on myTest object. That is why this refers to myTest in the first case.

在第二种情况下,你会像这样执行

In the second case, you would have executed like this

myTest.test1()()

myTest.test1()返回一个函数,你在没有任何当前对象的情况下调用。在这种情况下,JavaScript将确保将引用全局对象(在这种情况下为窗口)。

myTest.test1() returns a function and you are invoking without any current object. In that case, JavaScript will make sure that this will refer the global object (window in this case).

注意:但是,在严格模式下,将为 undefined ,在第二种情况下。您可以像这样确认

Note: But, in strict mode, this will be undefined, in the second case. You can confirm that like this

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

输出

this is global true
this is undefined false

但是如果你包括使用严格这样

"use strict";

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

输出

this is global false
this is undefined true

这篇关于Javascript这个关键字 - 内部功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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