概述
一个函数中this的指向是由挪用这个函数的环境来决议的。
全局
var a = 1; function b(){ var a = 2; console.log(this.a); }; b(); //1
<input type="text" value="4" onclick="b()" /> var value = 3; function b(){ console.log(this.value); }; b();//3 此时的b函数的环境是全局的
部分
var a = 1; var c = {a:3}; c.b = function(){ var a = 2; console.log(this.a); }; c.b();//3 //马上实行函数 由因而赋值,所以只实行了右侧的函数 var a = 1; var c = {a:3}; (c.b = function(){ var a = 2; console.log(this.a); })();//1
apply、call 和 bind 转变this指向
apply
参数
只能传两个参数,第一个参数a是
转变this指向的效果对象(在非严厉形式下,第一个参数为null或许undefined时会自动替换为指向全局对象),第二个参数是传给a的
参数鸠合(arguments[数组或类数组]);实例
var a = 1; var c = {a : 3}; function b(d,e){ var a = 2; console.log(this.a); console.log(d,e); }; b.apply(c);//3 undefined undefined b.apply();//1 undefined undefined b.apply(c,[5,6]);// 3 5 6
call
参数
第一个参数和apply()的第一个参数一样,差别的是apply()背面是吸收一个数组或类数组,call()背面是是吸收的参数列表。
实例
var a = 1; var c = {a : 3}; function b(d,e){ var a = 2; console.log(this.a); console.log(d,e); }; b.call(c);//3 undefined undefined b.call();//1 undefined undefined b.call(c,5,6);// 3 5 6
bind
参数
参数和call一样,差别的是 call()和apply()在挪用函数之后会马上实行,而bind()要领挪用并转变函数运行时上下文后,返回一个新的函数,供我们须要时再挪用。
实例
var a = 1; var c = {a : 3}; function b(d,e){ var a = 2; console.log(this.a); console.log(d,e); }; var b1 = b.bind(c); var b2 =b.bind(); var b3 =b.bind(c,5,6); b1();//3 undefined undefined b2();//1 undefined undefined b3()// 3 5 6