this的指向在函数定义的时候是确定不了的只有在函数执行的时候才能确定this到底指向谁。this指向上一级对象
1.函数调用,this指向window
var color = "red" function test() { var color = "yellow" console.log(this.color) //red console.log(this) //window } test()
1 var a = 8; 2 var c = { 3 a :10, 4 b:{ 5 a: 12, 6 fn: function() { 7 a: 13 8 console.log(this.a) //8 9 console.log(this) //window 10 } 11 } 12 } 13 var test = c.b.fn
14 test()
2.构造函数,this指向实例对象
1 function user(name, age) { 2 this.name = name 3 this.age = age 4 this.say = function() { 5 console.log(this.name) //wu 6 console.log(this) //user{name: 'wu'...} 7 } 8 } 9 var wus = new user('wu', 12) 10 wus.say()
1 function Fn() { 2 this.name = 'wu' 3 console.log(this) //Fn 4 } 5 var jia = new Fn() 6 console.log(jia.name) //wu
3.apply,call上下文调用, this指向传入的第一个参数(改变this指向)
1 var a = { 2 name:"wu", 3 fn:function(){ 4 console.log(this.name); //wu 5 } 6 } 7 var b = a.fn; 8 b.call(a);
var a = { name:"wu", fn:function(){ console.log(this); // window } } var b = a.fn; b.call(null);
1 var a = { 2 name:"wu", 3 fn:function(b,c){ 4 console.log(this.name); //wu 5 console.log(b+c); //12qw 6 } 7 } 8 var d = a.fn; 9 d.apply(a,[12,"qw"]);
4.方法调用,this指向调用对象
var a = 8; var c = { a :10, b:{ a: 12, fn: function() { a: 13 console.log(this.a) //12 console.log(this) //b } } } var test = c.b.fn()
1 var color = "red" 2 var test= { 3 color :"yellow", 4 getColor: function() { 5 console.log(this.color) //yellow 6 console.log(this) //test 7 } 8 } 9 test.getColor() // === window.test.getColor()
10 getColor() // is not defined