JavaScript中this的指向问题
2019-02-25 00:17
453 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_19915515/article/details/85332673
全局环境中的this指向
无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指代全局对象(不一定是window对象)。
var name = 'Mrs Right' console.log(this.name) // Mrs Right console.log(window.name) // Mrs Right
函数作用域
function func () { this.name = 'Mrs Right' var name2 = 'Mr Zhou' } console.log(this.name, name2) // undefined undefined func() console.log(this.name, name2) // Mrs Right undefined
从上面的代码来看,
func内部的this指向的还是window对象。但如果是在函数内部使用var来申明一个变量 则该变量不会得到提升。上面的代码在
nodejs环境执行则会输出两次
undefined。
var name = 'Mrs Right' function test () { // var self = this var name = 'Mr Zhou' var test2 = function () { console.log(name, this.name) // Mr Zhou undefined // console.log(name, this.name) // Mr Zhou MrsRight } test2() } test()
在函数
test2()内部调用不能以
this方式调用
test()函数外的内容,这时可以使用在
test函数定义
var self = this的方式来使用
test()中的
this内容。
var name = 'Mr Zhou' var obj = { name: 'Mrs Right', func: function () { console.log(this.name) } } obj.func() // Mrs Right
在一个
object内部定义
function,在任意处发起调用时,
this永远指向这个
object。
相关文章推荐
- 不要再问我 JavaScript this 的指向问题了
- javascript This指向问题简述
- JavaScript中setTimeout的作用域以及this指向问题
- javascript中this的指向问题
- javascript中this指向问题
- 【javascript 技巧】谈谈setTimeout的作用域以及this的指向问题
- 【javascript 技巧】谈谈setTimeout的作用域以及this的指向问题
- 关于javascript的this指向问题
- 关于javascript中的this更改指向问题
- JavaScript的三种this指向问题
- javascript里this的指向问题
- javascript中this指向问题的综合
- 关于JavaScript中的this指向问题总结篇
- javascript中this对象的指向问题
- JavaScript 的 this 指向问题深度解析
- javascript中的this指向问题
- JavaScript中this的指向问题
- javascript中this的指向问题
- 详解JavaScript中this的指向问题
- javascript中this 的指向问题(二)