在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一一对应。