this是Javascript语言的一个关键字。
它代表函数运行时,自动生成的一个内部对象。比如,
function test() { this.x = 1;}
this 是当前执行上下文中的一部分。
this永远指向函数的调用者。
随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。1.this指向的形式4种
a.如果是一般函数,this指向全局对象window;
b.在严格模式下"use strict",为undefined.
c.对象的方法里调用,this指向调用该方法的对象.
d.构造函数里的this,指向创建出来的实例.
e.在事件处理函数中,this指向触发事件的DOM对象
//afunction bar() { console.log(this);//一般函数,this指向全局对象window}bar();//bvar foo = function() { "use strict"; console.log(this);//表示使用严格模式;在严格模式下,为undefined}foo();//cvar name = 'tesla';var car = { name:"bmw", drive: function() { console.log(this); //object car console.log(this.name); //bmw var that = this;//定义一个that变量来存储this的值 setTimeout(function(){ //setTimeout是全局函数 console.log(this); //window console.log(this.name); //tesla console.log(that); //object car console.log(that.name); //bmw },1000); }}car.drive();//dvar name = 'tom';//声明一个函数function person() { console.log(arguments.length); this.name = arguments[0]; this.age = arguments[1]; console.log(this); console.log(this.name); console.log(this.age);}person(); //0 window undefined undefinedvar tom = new person('amy',20); //2 person -> tom amy 20//e//先遍历 '.tr-s'$('.tr-s').each(function (index,item) { //再遍历 '.tr-s' 下的 'td-t' $(this).find('.td-t').each(function (index_s,item_s) { //index_s 是下标 //item_s 是对应的对象 })})
2.改变this的指向
在JS中一切皆对象,函数也是对象,既然是对象就有属性和方法,在JS中所有的方法都有两个方法call(),apply()
我们可以使用这两个方法来显示更改函数中this的指向,
call、apply这两个函数的共同特点:改变并立即执行。区别就是传参方式不同
call是一个一个传入apply是传入一个数组,一次性传完。.call(), call(thisScope, arg1, arg2, arg3...)
.apply(), apply(thisScope, [arg1, arg2, arg3...]);两个参数
在ES5中新增了bind(),该方法也是强制更改this指向
而bind 改变this的指向,返回的是函数
.bind() bind(thisScope, arg1, arg2, arg3...)
但是bind和call、apply的区别是bind更改this后不会立即执行,它会返回一个新函数。
bind传参也是一个一个的传入
var obj = { name:'tom', age:20}function show(a,b){ console.log(a,b);}//独立调用show(1,2);//强制更改this指向为obj 并立即执行该函数show.call(obj,1,2);show.apply(obj,[1,2]);//强制更改this指向obj,不会立即执行,它会返回一个新函数,需要主动去执行这个函数show.bind(obj,1,2)();
箭头函数的this
我们使用foo函数的call方法改变了foo函数调用时函数体内this的指向({id: 42}这个对象),但setTimeout回调函数中的this依旧指向window对象(因为在全局环境中运行)。
普通函数
function foo() { console.log("id1:", this.id); console.log("this1:", this); setTimeout(function() { console.log("id2:", this.id); console.log("this2:", this); }, 0);}var id = 21;foo();// id1: 21 ; this1: window ; id2: 21 ; this2: windowfoo.call({id: 42});// id1: 42 ; this1: {id: 42} ; id2: 21 ; this2: window
箭头函数
function foo() { console.log("id1:", this.id); console.log("this1:", this); setTimeout(() =>{ console.log("id2:", this.id); console.log("this2:", this); }, 0);}var id = 21;foo();// id1: 21 ; this1: window ; id2: 21 ; this2: windowfoo.call({id: 42});// id1: 42 ; this1: {id: 42} ; id1: 42 ; this1: {id: 42}
在这里直接给出结论:
箭头函数根本没有自己的this,导致内部的this指向了外层代码的this,这个指向在定义时就已经确定而不会在调用时指向其执行环境的(变量)对象。