_React$Component.call.apply(_React$Component, [this].concat(args))理解

在React-Router打包后的react-router-dom.js文件中,看到过_React$Component.call.apply(_React$Component, [this].concat(args)) || this;今天就聊聊Function.prototype.call.apply(),代码中源码是:

var BrowserRouter =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(BrowserRouter, _React$Component);

  function BrowserRouter() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.history = history.createBrowserHistory(_this.props);
    return _this;
  }

  var _proto = BrowserRouter.prototype;

  _proto.render = function render() {
    return React.createElement(reactRouter.Router, {
      history: this.history,
      children: this.props.children
    });
  };

  return BrowserRouter;
}(React.Component);

为了更好的理解Function.prototype.call.apply,先出一个题:

    Function.prototype.call.apply(Math.floor, [undefined, 11.11]);

打印结果:11

解析:..apply方法,相当于将.call方法中的this指向Math.floor,即Math.floor.call(...[undefined, 11.11]),则Math.floor.call(undefinde, 11.11),即Math.floor中的this指向undefined,传入的参数是11.11,即结果为11。

可能不是好理解,下面我们一步一步来讲解。

Function.prototype.call可以写成:

Function.prototype.call = function(_this, ...args) {
    coinst func = this.bind(_this);
    func(...args);
}

那么this指向Math.floor,_this指向undefined,那么func(...args)相当于Math.floor(11.11);

所以:_React$Component.call.apply(_React$Component, [this].concat(args))就很好理解了。相当于把_React$Component的this指向BrowserRouter实例化,props/context/updater由...args一一对应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值