全局环境中的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
。