this绑定规则

2020-09-13  本文已影响0人  仔崽06

1. this默认绑定

1.全局环境下this指向window

console.log(this) //window

2.函数独立调用时,函数的内部this也指向window

function fn(){
   console.log(this) //window
}
fn() 等同于window.fn()

3.被嵌套函数独立调用时,函数里的this也指向window

let obj={
    a:1,
    foo:function(){
        function test(){
           console.log(this)  //window
        }
        test()
    }
}
obj.foo()

4.自执行函数this也指向window

function foo(){
     (function(){
        console.log(this)  //window
     })()
}
let obj={
    a:1,
    foo:foo
}
obj.foo()

5.闭包this默认指向window

let obj={
  a:1,
  foo:function(){
       return function test(){
           console.log(this) //window
       } 
  }
}
obj.foo()

2.this的隐式绑定

1.当函数当做对象的方法来调用,this指向了当前对象

let a=1
function foo(){
   console.log(this.a) //2 //4
}
let obj={
    a:2,
    foo:foo,
    obj1:{
       a:4,
       foo:foo
    }
}
obj.foo() //this指向obj
obj.obj1.foo() //this指向obj1

3.this隐式丢失(是指被绑定的函数丢失了绑定对象,从而使this指向window)

1.函数别名
var a=0;
function foo(){
     console.log(this.a) //window 0
}
let obj={
   a:2,
   foo:foo
}
var bar=obj.foo;
bar()
2.参数传递
var a=0;
function foo(){
   console.log(this.a)
}
function bar(fn){
    fn()
}
let obj={
   a:2,
   foo:foo
}
bar(obj.foo)
3.内置函数
setTimeout(function(){
     console.log(this)  //window
},1000)
setInterval(()=>{
    console.log(this) //window
})
4.间接调用
function foo(){
    console.log(this.a)  //window
}
var a=2;
var obj={
    a:3,
    foo:foo
}
let p={a:4,foo:''};
(p.foo=obj.foo)()
(false || obj.foo)()
(1,obj.foo)()

4.显示绑定

1.call(),apply(),bind()
var a=0;
function foo(){
  console.log(this.a) //obj
}
var obj={
   a:3
 }
foo.call(obj)
let fn=foo.bind(obj);
fn()
2.硬绑定
var a=0;
function foo(){
   console.log(this.a)
}
var obj={a:2}
var bar=function(){
    foo.call(obj) //obj
} 
bar()
setTimeout(bar,2000)
bar.call(window)
3.数组forEach、map等
let id='window'
function fn(el){
   console.log(el,this.id)
}
let obj={ id:'fn'}
let arr=[1,2,3]
arr.forEach(fn) //this指向window
arr.forEach(fn,obj) //this指向obj

5.new 绑定(new this指向当前实例化对象)

function Fn(){
   console.log(this) //fn
}
let fn=new Fn()

function fn2(){
  console.log(this); //fn
  return {
      name:'mjj'
  }
}
let fn=new fn2();

6.严格模式下this

1.严格模式,独立调用函数 this指向undefined
function fn(){
      'use strict'
      console.log(this)  //undefined
}
fn()
 
//2.严格模式下函数apply()和call()内部this始终是它们的第一个参数
 let color='red'
  function showColor(){
     'use strict'
     console.log(this);  //undefined
     console.log(this.color)
  }
showColor.call(undefined)
上一篇 下一篇

猜你喜欢

热点阅读