码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript严格模式下this指向

时间:2017-12-02 17:53:46      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:bsp   family   text   col   char   mod   图片   blog   报错   

一般认为:严格模式下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>

控制台输出报错:

技术分享图片

 

JavaScript严格模式下this指向

标签:bsp   family   text   col   char   mod   图片   blog   报错   

原文地址:http://www.cnblogs.com/mengfangui/p/7954585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!