小知识:开启严格模式 ---- 脚本开启   函数内部开启

                均使用'use strict'(需写在顶部,例子见下文)

1. 全局执行环境

在严格模式和非严格模式下this指向均为全局对象(window)

2. 函数内部

2.1 直接调用

严格模式:undefined

非严格模式:window

2.2 对象调用

对象本身(严格模式和非严格模式均是)

代码如下:

<script>
        // 开启严格模式 -- 脚本开启   函数内部开启  均通过 'use strict'

        // 确认this指向
        // 1. 全局执行环境
        // 'use strict'
        console.log('全局执行环境', this)

        // 2. 函数内部
        // 2.1 直接调用
        function fun() {
            // 'use strict'
            console.log('函数内部-直接调用-严格模式', this)  // undefined
            console.log('函数内部-直接调用-非严格模式', this)  // window
        }
        fun()

        // 2.2 对象调用
        const obj = {
            name: 'this指向',
            fn() {
                // 'use strict'
                console.log('函数内部-对象调用-严格模式', this)  // 对象本身
                console.log('函数内部-对象调用-非严格模式', this)  // 对象本身
            }
        }
        obj.fn()

    </script>

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部