this是函数内部的一个自动生成的对象,随着使用场景的不同,this的指向也不同,下面列举一些this指向的事例。
事件处理函数内部的 this
事件处理函数内部 this 指向 事件源 DOM 对象
1 2 3 4 5 6 7 8 9 10 11 12
| var lis = document.querySelectorAll('li'); lis.forEach(function (li) { li.addEventListener('click', function () { console.log(this); var that = this; setTimeout(function () { console.log(this, that); }, 1000); }); });
|
定时器函数内部的 this & 普通函数内部的 this
定时器函数内部 this 指向 window
普通函数内部 this 指向 window
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| setTimeout(function () { console.log(this); }, 1000); function fn () { console.log(this); var handle = function (item, index) { console.log(this); }; ;[1, 2, 3].forEach(handle); }; fn();
|
构造函数中 this
构造函数中 this 指向实例对象
1 2 3 4 5 6 7 8 9 10
| function fn(){}; fn.prototype.sayHello = function () { console.log(this); }; fn.prototype.sayHello(); var instance = new fn(); instance.sayHello();
|
对象中函数 this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function fn(){ console.log(this); }; var obj = { foo: 'hello', sayFoo: fn, sub: { foo: 'world', sayFoo: fn }; }; obj.sayFoo(); obj.sub.sayFoo(); fn(); new fn();
|
当然,还有其他情况可以改变函数内部 this 指向–>函数的call、apply、bind方法
函数的call方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function fn(){ console.log(this); }; var obj={foo:'bar'}; fn.call(this); fn.call(obj); function Person(){ fn.call(this); }; Person(); new Person(); function fn(){ console.log(arguments); var args=[].slice.call(arguments,0); args.forEach(function(item,index){ console.log(item,index); }); }; fn(21,41,56,62,2,5);
|
函数的apply方法
1
| apply方法和call方法作用一样,区别在于call传入的参数是单个元素,而apply传入的参数是一个数组。
|
函数的bind方法
1 2 3 4 5 6 7 8 9
| var obj = {foo:'bar'}; function fn(x,y,z){ console.log(this,x,y,z); }; var newFn=fn.bind(obj,1); newFn(4,5);
|