this指向分几种情况,不光是谁调用就指向谁
(一)谁调用就指向谁,jquery中一个简单的例子(this指向调用者)
$(".box-ul li").click(function(){ $(this).css('color','#ff8300').siblings().css('color','#333') })
(二) this在函数中的指向
(1) 函数内变量没有赋值
var x = 1 function test(){ return this.x } test() console.log(x); // 1 this指向window (2)函数内变量赋值 var x = 1 function test(){ this.x = 0 } test() console.log(x); // 0 this指向调用者test (3)多个函数调用,this指向最后调用的 var x = 1 function test(){ this.x = 0; } function test1() { this.x = 2 } test() test1() console.log(x); // 2 如果先调用test(),后调用test1(),则this指向test1() ;反之,this指向test()
(三) 对象中this的指向
function test2() { return this.a } var o = {} o.a = 1 o.action = test2 // 这一行代码把this指向了对象o console.log(o.action())
(四) 构造函数中this的指向
function Person(name,age) { this.name = name this.age = age } var p1 = new Person('lily',24) console.log(p1.name) // lily this 指向p1(实例化对象) var p1 = new Person('Lucy',24) console.log(p2.name) // Lucy this 指向p1(实例化对象)
(五) 改变this指向
改变this指向 call(this,param1,param1,....) apply(this,[param1,param2,....]) (这两个方法的作用是:在一个对象中调用另一个对象) var a = "111" function test3() { return this.a; } var obj = {} obj.a = 1 obj.b = test3 console.log(obj.b.call(),'this指向是window') console.log(obj.b.call(o),' this指向是对象o')
(六) 特殊情况(函数自调的时候,this指向window)
var number = 1; var obj = { number:2, showNumber:function() { this.number = 3; // 函数自调的时候,this指向window (function(){ console.log(this.number) })(); console.log(this.number) } } obj.showNumber(); // 1 3