JavaScript严格模式下this指向

严格模式下this指向
本文详细解释了JavaScript严格模式下this指向的规则。在函数体内部,this不允许指向全局对象,但直接在全局作用域中则可以。文章通过具体示例代码展示了不同情况下this指向的变化。

一般认为:严格模式下this不允许指向全局对象。是函数体是否处于严格模式!

如:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

 

需要说明的是:本身指向全局的this是没有问题的

示例代码:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>严格模式下this指向</title>
    </head>

    <body>
        <script type="text/javascript">
            'use strict';
            console.log(this);
        </script>
    </body>

</html>

控制台输出为window对象(全局对象)

严格模式下this不允许指向全局对象是指在函数内部,如下示例代码:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>严格模式下this指向</title>
    </head>

    <body>
        <script type="text/javascript">
            'use strict';

            function F() {    
                this.a = 1;   //这种指向全局的this不对
            };
            F();
        </script>
    </body>

</html>

控制台输出报错:

 

补充(2017-12-14):

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

!function(){
    console.log(this)//undefined
}();

setTimeout(function(){
    console.log(this) //window
},0);

function a(){
    console.log(this);
}
a(); //undefined

setTimeout 是window的方法,setTimeout 在调用传入函数的时候,如果这个函数没有指定了的 this,那么它会做一个隐式的操作—-自动地注入全局上下文window

setTimeout(function(){
              console.log(111111)
          },1000)

window.setTimeout(function(){
              console.log(111111)
          },1000)

上述2个代码是相同的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值