this 函数执行上下文

this 使用于函数体中,是指调用函数的对象.

函数调用时 有两种方式

  1,明确调用函数的主体  

    例如 window.func1   window就是调用的主体,在 func1 中的this就指向window

  2,直接执行函数

    比如 func2()  

      在严格模式下, func2 内部的 this 就是 undefined  // 很多浏览器执行都不是这样

      在非严格模式下, func2 内部的 this 就指向 执行上下文 .

        如果外层没有函数,就指向 window

        有外层函数,就指向外层函数的 执行上下文 this

有一种特殊函数使用时 this的指向与普通的函数不同,那就是 箭头函数

语法

  ( 参数值 ) => { 函数体 }

箭头函数体中的 this 指向的是 创建时的执行上下文 , call , apply  , bind 都无法修改

简单验证

var b = {name:'b'}
window.name = 'window'

function a(){
    console.log(this.name)
}

function _a(){
    this.name = '_a'
    a()
}

a();// window
a.call(b);// b
_a();// _a

明确调用函数的主体的方式有以下几种:

  1, 对象或直接量 . 函数()

  2, 函数.call(对象,参数1,参数2...)

  3,函数.apply(对象,参数数组)

  4,反射 Reflect.apply( 函数 , context , argumentArray )

    相当于 Function.prototype.apply.call(  函数 , context , argumentArray  )

  5, 函数.bind(对象) 

    需要注意一点:

      上面几种方式都是直接调用函数执行的,而bind却是返回一个函数,并且返回的函数再次执行bind时也不会再改变上下文的绑定

通过apply来实现bind函数,这对理解bind有很大的帮助

Function.prototype._bind = function(context){
    var that = this,param = Array.prototype.slice.apply(arguments,[1]);
    return function(){
        that.apply(context,param);
    }
}
原文地址:https://www.cnblogs.com/xiaxiaodong/p/8278781.html