this
一. this指向
-
在绝大多数情况下,函数的调用方式决定了
this
的值(运行时绑定)。 -
this
不能在执行期间被赋值,并且在每次函数被调用时this
的值也可能会不同。 -
ES5 引入了 bind 方法来设置函数的
this
值,而不用考虑函数如何被调用的。 -
ES2015 引入了箭头函数,箭头函数不提供自身的 this 绑定(
this
的值将保持为闭合词法上下文的值)。
this指向谁
- 当前执行上下文(global、function 或 eval)的一个属性,在非严格模式下,总是指向一个对象,在严格模式下可以是任意值。
二. 全局上下文
-
无论是否在严格模式下,在全局执行环境中(在任何函数体外部)
this
都指向全局对象。 -
// 在浏览器中, window 对象同时也是全局对象: console.log(this === window); // true 复制代码
-
可以使用globalThis获取全局对象,不管代码是否在当前上下文执行。
三. 函数上下文
- 在函数内部,
this
的值取决于函数被调用的方式
1. 非严格模式
-
因为下面的代码不在严格模式下,且 this 的值不是由该调用设置的,所以 this 的值默认指向全局对象
-
function f1() { return this; } // 在浏览器中,全局对象是window console.log(f1() === window); // true // 在Node中: console.log(f1() === globalThis);// true // 通过window调用,this指向调用该函数的window对象 console.log(window.f1() === window);// true 复制代码
-
// this指向调用它的obj对象 let obj = { a: 10, f1: function() { return this.a; }, }; console.log(obj.f1()); // 10 复制代码
2. 严格模式
-
在严格模式下,如果进入执行环境时没有设置
this
的值,this
会保持为undefined
-
function f2(){ "use strict"; // 这里是严格模式 return this; } console.log(f2()); // undefined console.log(window.f2());// 打印window对象 复制代码
四. 类上下文
-
this
在 类 中的表现与在函数中类似,因为类本质上也是函数,但也有一些区别和注意事项。 -
在类的构造函数中,
this
是一个常规对象。类中所有非静态的方法都会被添加到this
的原型中 -
静态方法不是 this 的属性,它们只是类自身的属性。
-
class Example { constructor() { // Object.getPrototypeOf(obj),该方法接收一个对象作为参数,并返回该对象的原型 const proto = Object.getPrototypeOf(this); // Object.getOwnPropertyNames(obj)方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性但不包括Symbol值作为名称的属性)组成的数组。 console.log(Object.getOwnPropertyNames(proto)); } first(){} second(){} static third(){} } new Example(); // ['constructor', 'first', 'second'] 复制代码
派生类
派生类使用this
-
派生类的构造函数没有初始的
this
绑定。在构造函数中调用super()
会生成一个this
绑定,并相当于执行如下代码,Base为基类: -
this = new Base(); 复制代码
-
在调用
super()
之前引用this
会抛出错误。
派生类返回
-
派生类不能在调用super()之前返回,除非构造函数返回的是一个对象,或者根本没有构造函数
-
class Base {} class Good extends Base {} class AlsoGood extends Base { constructor() { return { a: 5 }; } } class Bad extends Base { constructor() {} } console.log(new Good()); // good console.log(new AlsoGood()); // {a:5} console.log(new Bad());// ReferenceError 复制代码
-
class Bad extends Base { constructor() { super() } } console.log(new Bad());// Bad() 复制代码
五. this和对象转换
1. call()方法
-
call(obj,arguments)
-
第一个参数是将本身的this赋值给调用该方法的函数或对象的this
-
后面的参数是调用函数本身的参数
-
function add(c=2, d=3) { return this.a + this.b + c + d;}var o = { a: 1, b: 3 };console.log(add.call(o,20,30))// 54 复制代码
2. apply()方法
-
与call()方法类似,只是后面的参数以数组形式呈现
-
console.log(add.apply(o,[10,30]))// 44 复制代码
非严格模式下
-
在非严格模式下使用
call
和apply
时,如果用作this
的值不是对象,则会被尝试转换为对象。 -
null
和undefined
被转换为全局对象。 -
原始值如
7
或'foo'
会使用相应构造函数转换为对象。 -
console.log(add.apply(null))// NaN// this会被转换成window,由于window.a=undefined,所以undefined+undefined+2+3=NaN // 如果提前设置window.a和window.b则可以打印出来 复制代码
-
console.log(add.apply(7))// NaN// this会被转换成new Number(7),由于Number.a=undefined,所以undefined+undefined+2+3=NaN// 如果是return this+c+d,则可打印出来 复制代码
3. bind方法
-
ECMAScript 5 引入了
Function.prototype.bind()
。调用f.bind(someObject)
会创建一个与f
具有相同函数体和作用域的函数。 -
注意: 但是在这个新函数中,
this
将永久地被绑定到了bind
的第一个参数,无论这个函数是如何被调用的。 -
注意: bind只生效一次
-
function f(){ return this.a;}var g = f.bind({a:"azerty"});// 该函数体g的this已经被永久的绑定为{a: "azerty"}这个对象,后续绑定this将不会再变动console.log(g()); // azertyvar h = g.bind({a:'yoo'}); // 函数体g的this已经被永久绑定为{a: "azerty"}这个对象了,h的this转换不生效,同为g函数体的this!console.log(h()); // azertyvar t = f.bind({a:'yoo'}); // 函数体f没有调用过其他函数的bind方法,this可动态变换,可多次调用bind方法创建相同函数体和转换this!console.log(t()); // yoovar o = {a:37, f:f, g:g, h:h,t:t};console.log(o.a, o.f(), o.g(), o.h(),o.t()); // 37, 37, azerty, azerty,yoo 复制代码
六. 箭头函数
全局对象
-
在箭头函数中,
this
与封闭词法环境的this
保持一致。在全局代码中,它将被设置为全局对象: -
var globalObject = this; var foo = () => this; let obj = { a: 2, arrowFun: foo, }; function test() { let obj1 = obj; return obj1.arrowFun(); } console.log(foo() === globalObject); // true console.log(obj.fun() === globalObject); // true console.log(test() === globalObject);// true,函数自调用,其this默认为window对象 复制代码
-
如果将
this
传递给call
、bind
、或者apply
来调用箭头函数,它将被忽略。不过你仍然可以为调用添加参数,不过第一个参数(thisArg
)应该设置为null
。 -
// 尝试使用call来设定thisconsole.log(foo.call(obj) === globalObject); // true,因为this转移失效了// 尝试使用bind来设定thisfoo = foo.bind(obj);console.log(foo() === globalObject); // true,因为this转移失效了 复制代码
-
无论如何,
foo
的this
被设置为他被创建时的环境(在上面的例子中,就是全局对象)。
局部对象
-
这同样适用于在其他函数内创建的箭头函数:这些箭头函数的
this
被设置为封闭的词法环境的。 -
// bar返回一个函数,// 这个函数返回this,// 这个返回的函数是以箭头函数创建的,// 所以它的this被永久绑定到了它外层函数的this。// 它外层的匿名函数的this指向obj// bar的值可以在调用中设置,这反过来又设置了返回函数的值。var obj = { bar: function() { var x = (() => this); return x; }};// 作为obj对象的一个方法来调用bar,把它的this绑定到obj。var fn = obj.bar();//所以返回函数的this也指向objconsole.log(fn() === obj); // true// 但是注意,如果你只是引用obj的方法,// 而没有调用它var fn2 = obj.bar; // 这时fn2=function() { // var x = (() => this); // return x; // } // 这是的this被绑定到它外层函数的this,外层函数没被调用执行,this默认指向window// 那么调用箭头函数后,this指向window。 console.log(fn2()() == window); // true // fn2()=()=>this // fn2()()==window 复制代码
七. 作为对象的方法
-
当函数作为对象里的方法被调用时,该函数的
this
被设置为调用该函数的对象。 -
var o = { prop: 37, f: function() { return this.prop; }};console.log(o.f()); // 37 复制代码
-
这样的行为完全不会受函数定义方式或位置的影响
-
我们也可以先定义函数,然后再将其附属到
o.f
。 -
var o = {prop: 37};function independent() { return this.prop;}o.f = independent;console.log(o.f()); // 37 复制代码
-
this
的绑定只受最接近的成员引用的影响。 -
o.b = {g: independent, prop: 42};console.log(o.b.g()); // 42 复制代码
八. 原型链中的 **this**
-
如果该方法存在于一个对象的原型链上,那么
this
指向的是调用这个方法的对象,就像该方法就在这个对象上一样。 -
var o = { f: function() { return this.a + this.b; }};var p = Object.create(o);p.a = 1;p.b = 4;console.log(p.f()); // 5 复制代码
-
对象
p
没有属于它自己的f
属性,它的f
属性继承自它的原型。虽然最终是在o
中找到f
属性的,这并没有关系; -
因为
f
是作为p
的方法调用的,所以它的this
指向了p
九. getter 与 setter 中的 this
-
用作
getter
或setter
的函数都会把this
绑定到设置或获取属性的对象。 -
function sum() { return this.a + this.b + this.c;}var o = { a: 1, b: 2, c: 3, get average() { return Math.ceil((this.a + this.b + this.c) / 3); }};Object.defineProperty(o, 'sum', { get: sum, enumerable: true, configurable: true});console.log(o.average, o.sum); // 2, 6 复制代码
十. 作为构造函数
-
当一个函数用作构造函数时(使用new关键字),它的
this
被绑定到正在构造的新对象。 -
/* * 构造函数这样工作: * * function MyConstructor(){ * // 函数实体写在这里 * // 根据需要在this上创建属性,然后赋值给它们,比如: * this.fum = "nom"; * // 等等... * * // 如果函数具有返回对象的return语句, * // 则该对象将是 new 表达式的结果。 * // 否则,表达式的结果是当前绑定到 this 的对象。 * //(即通常看到的常见情况)。 * } */function C(){ this.a = 37;}var o = new C();console.log(o.a); // 构造函数C的this被绑定到正在构造的新对象O上,37function C2(){ this.a = 37; return {a:38};}o = new C2();console.log(o.a); // 构造函数C返回一个对象,并将该对象赋值给正在构造的新对象O,38function C3(){ this.a = 37; return 123;}o = new C3();console.log(o.a); // 构造函数C有返回,但不是一个对象,结果如第一种方式,37 复制代码
十一. 作为一个DOM事件处理函数
-
当函数被用作事件处理函数时,它的
this
指向触发事件的元素(一些浏览器在使用非addEventListener
的函数动态地添加监听函数时不遵守这个约定)。 -
// 被调用时,将关联的元素变成蓝色function bluify(e){ console.log(this === e.currentTarget); // 总是 true // 当 currentTarget 和 target 是同一个对象时为 true console.log(this === e.target); this.style.backgroundColor = '#A5D9F3';}// 获取文档中的所有元素的列表var elements = document.getElementsByTagName('*');// 将bluify作为元素的点击监听函数,当元素被点击时,就会变成蓝色,采用事件冒泡for(var i=0 ; i<elements.length ; i++){ elements[i].addEventListener('click', bluify, false);} 复制代码
十二. 作为一个内联事件处理函数
-
当代码被内联 on-event 处理函数 调用时,它的
this
指向监听器所在的DOM元素: -
<button onclick="alert(this.tagName.toLowerCase());"> Show this</button> 复制代码
-
上面的 alert 会显示
button
。注意只有外层代码中的this
是这样设置的: -
<button onclick="alert((function(){return this})());"> Show inner this</button> 复制代码
-
在这种情况下,没有设置内部函数的
this
,所以它指向 global/window 对象(即非严格模式下调用的函数未设置this
时指向的默认对象,严格模式下为undefined)。
十二. 类中的this
-
class Car { constructor() { // 将sayBye方法的this永远绑定为Car的this this.sayBye = this.sayBye.bind(this); } sayHi() { console.log(`Hello from ${this.name}`); } sayBye() { console.log(`Bye from ${this.name}`); } get name() { return 'Ferrari'; }}class Bird { get name() { return 'Tweety'; }}const car = new Car();const bird = new Bird();car.sayHi(); // Hello from Ferraribird.sayHi = car.sayHi; // 引用car的方法但没有调用,方法内的this 默认指向调用该方法的对象bird.sayHi(); // Hello from Tweety// 由于Car的sayBye方法的this永远绑定为Car的this,即使引用不调用,this的值都不能再改变了bird.sayBye = car.sayBye;bird.sayBye(); // Bye from Ferrari 复制代码