Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写bind #4

Open
aochengcheng opened this issue Apr 7, 2020 · 0 comments
Open

手写bind #4

aochengcheng opened this issue Apr 7, 2020 · 0 comments

Comments

@aochengcheng
Copy link
Owner

aochengcheng commented Apr 7, 2020

this的四种绑定规则

  1. 默认绑定
    独立调用函数时, this 指向全局对象,如果使用严格模式,那么全局对象无法使用默认绑定, this 绑定至 undefined 并抛错

  2. 隐式绑定
    当函数作为引用属性被添加到对象中,隐式绑定规则会把函数调用中的 this 绑定到这个上下文对象

  3. 显式绑定
    运用apply call 方法,在调用函数时候绑定this,也就是指定调用的函数的this值

  4. new绑定
    就是使用new操作符的时候的this绑定

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

MDN 给出bind方法的定义:
bind() 方法创建一个新函数,当这个新函数被调用时其this置为提供的值。,其参数列表前几项置为创建时指定的参数序列。

bind() 函数会创建一个新 绑定函数 , 绑定函数 与被调函数具有相同的函数体(在 ECMAScript 5 中)。调用 绑定函数 通常会导致执行 包装函数 绑定函数 也可以使用new运算符构造:这样做就好像已经构造了目标函数一样。提供的 this 值将被忽略,而前置参数将提供给模拟函数

总的来说bind有如下三个功能点:

  1. 改变原函数的 this 指向,即绑定上下文,返回原函数的拷贝
  2. 当 绑定函数 被调用时,bind的额外参数将置于实参之前传递给被绑定的方法。
  3. 注意,一个 绑定函数 也能使用 new 操作符创建对象,这种行为就像把原函数当成构造器,thisArg 参数无效。也就是 new 操作符修改 this 指向的优先级更高。

开始实现一个bind

输入:接受一个或多个参数,第一个是要绑定的上下文,额外的参数当做绑定函数的参数。
输出:返回原函数的拷贝,即返回一个函数,这个函数具有原函数一样的功能

 Function.prototype.myBind = function(context, ...arg1) {
     if (typeof this !== 'function') throw new TypeError('not a function')
    const _self = this
    const fnNop = function () {} // 定义一个空函数
    function rf(...arg2){
       const args = [...arg1, ...arg2]
       const _this = this instanceof rf ? this : context
       _self.apply(_this, args)
    }
   fnNop.prototype = _self.prototype
   rf.prototype = new fnNop()
   return _self
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant