javascript - 对省略'this'关键字的困惑

Kac*_*acy 1 javascript jquery

有人可以解释以下行为吗?前两个示例按预期工作,但为什么最后一个示例不起作用?我想了解当我省略'this'关键字时发生了什么.好像我能够在前两个例子中省略它.

提醒您好:

$(document).ready(
    function()
    {
        hello = 'hello';

        function sayHello()
        {
            alert( this.hello );
        }

        sayHello();
    }
);
Run Code Online (Sandbox Code Playgroud)

提醒您好:

$(document).ready(
    function()
    {
        hello = 'hello';

        function sayHello()
        {
            alert( hello );
        }

        sayHello();
    }
);
Run Code Online (Sandbox Code Playgroud)

警告声明出错: Uncaught ReferenceError: hello is not defined

$(document).ready(
    function()
    {
        this.hello = 'hello';

        function sayHello()
        {
            alert( hello );
        }

        sayHello();
    }
);
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 6

全局变量自动成为window对象的属性.当你在没有指定任何上下文的情况下调用函数(即functionName()代替something.functionName())时,默认上下文也是window对象.

你的第一个功能是设置全局变量hello,它与window.hello.sayHello()然后该功能发出警报this.hello,这也与window.hello因为相同this == window.

第三种情况不同,因为你的外部函数被调用$(document).ready().当jQuery调用事件处理函数时,上下文是事件的目标.在这种情况下,this == document当你这样做时:

this.hello = 'hello';
Run Code Online (Sandbox Code Playgroud)

它相当于:

document.hello = 'hello';
Run Code Online (Sandbox Code Playgroud)

这不会设置全局变量hello,因此sayHello不会访问它.这将等效地工作:

$(document).ready(
    function()
    {
        this.hello = 'hello';

        function sayHello()
        {
            alert( document.hello );
        }

        sayHello();
    }
);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)