【问题标题】:Why "this" inside of a function's returning object window为什么在函数的返回对象窗口中出现“this”
【发布时间】:2014-04-08 15:55:31
【问题描述】:

在 javascript 中有两种类型的范围命名 功能范围 全局范围

现在我正在执行这段代码

function abc()
{
alert(this);
}
abc();

abc 调用返回我 [object Window] 为什么??函数创建了另一个范围,所以为什么它代表窗口

【问题讨论】:

标签: javascript function this


【解决方案1】:

this,在任何函数内部,都是调用函数的对象。在您的情况下,您没有在任何对象上调用它。因此,默认情况下this 引用global 对象,在您的浏览器中,它是window 对象。

但是在strict 模式下,如果你这样调用它,this 将是undefined

"use strict";
function abc() {
    console.log(this);    // undefined
}
abc();

或者

function abc() {
    "use strict";
    console.log(this);   // undefined
}
abc();

【讨论】:

    【解决方案2】:

    你的函数在 global(window) 对象下。我的意思是,

    function abc()
    {
        alert(this);
    }
    abc(); 
    // or You can either call by
    window.abc()
    

    你可以在自定义对象下编写你的函数

    // Function under custom object
    var customObj = {
        abc : function () {
            alert(this);
        }
    };
    customObj.abc()
    

    【讨论】:

      【解决方案3】:

      this 关键字是指函数所属的对象,如果函数不属于任何对象,则为窗口对象。

      参考

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

      【讨论】:

        猜你喜欢
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        • 2012-10-24
        • 1970-01-01
        • 2017-07-26
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多