小知识:开启严格模式 ---- 脚本开启 函数内部开启
均使用'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>
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 如何确定this指向
发表评论 取消回复