函数中this的指向是不确定的,只有在函数执行时才能确定,它指向调用该函数的对象
var a = 'a'
var b = 'b'
function f(){
console.log(this) //window
console.log(this.a) //a
console.log(this.b) //b
console.log(this.c) //undefined this指向window,window中没有c
var a = 'aa'
b = 'bb'
var c = 'cc'
console.log(this.a) //a 函数中定义变量a,但是this.a为window.a
console.log(this.b)//bb window中的变量b在函数体内被改变
console.log(this.c) //undefined this指向window,window中没有c
console.log(window.a) //a
console.log(window.b) // bb window中的变量b在函数体内被改变
console.log(window.c) //undefined this指向window,window中没有c
console.log(a) //aa
console.log(b) //bb
console.log(c) //cc
}
f()
这里调用函数f的对象是window,函数内部的this为window
var o = { name: 'lll', getName:function(){ console.log(this.name) } } o.getName() // lll var m = o.getName m() //此时this指向window
构造函数
function P(){ this.name = 'ppp' } var p = new P() console.log(p.name)
new关键字改变this的指向