您的位置:首页 > Web前端 > JavaScript

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: