this指向

139 阅读1分钟

1.默认绑定规则

console.log(this === window) // true

function test(){
console.log(this === window) // true
}
test(); // 等价于 window.test();

2.隐式绑定规则:谁调用就指向谁

var a = 2;
var foo = {
 a: 3,
 test: function () {
   console.log(this);  // foo
   function test() {
     console.log(this); // window
   }
   test();  // 等价于 window.test();
 },
};
foo.test();

3.显示绑定规则 bind call apply

function test(a,b,c){
console.log(a,b,c);
}
var a = 2
var obj = {
a:3,
test:test
}

var bar = obj.test
bar() // this指向window
bar.call(obj,1,2,3); // this指向obj
bar.apply(obj,[1,2,3]); // this指向obj
bar.bind(obj)(1,2,3); // this指向obj

// **注意**
bar.call(1,2,3); // this指向Number
bar.call(false,2,3); // this指向Boolean
bar.call(null,2,3); // this指向window 因为null没有包装类,绑定失败,即为window
bar.call(undefined,2,3); // this指向window 因为undefined没有包装类,绑定失败,即为window

// IIFE立即执行函数默认执行window
(function(){
  console.log(this) // window
})()
// IIFE立即执行函数可以用通过call apply bind修改this指向
(function(){
  console.log(this) // obj
}).call(obj)

 (function(){
  console.log(this) // obj
}).apply(obj)

 (function(){
  console.log(this) // obj
}).bind(obj)()

  1. new 绑定
function Person(){
this.a = 1
return this // 当返回是引用类型 可以省略
// return {} 返回值会发生改变 返回{}
// return 1 默认还是返回this
}

let person = new Person()
console.log(person) // Person {a: 1}

  1. 箭头函数中的"this"
  • 默认绑定外层的this
  • 不能用call方法修改里面的this

总结:

  1. this有四种绑定方式

  2. this优先级:new>显式绑定>隐式绑定>默认绑定

  3. 箭头函数的this无法改变,只与外层this一致