鍍金池/ 問答/HTML/ react源碼寫法疑惑

react源碼寫法疑惑

// React v16.2 
// ReactBaseClasses.js

/**
 * Base class helpers for the updating state of a component.
 */
function PureComponent(props, context, updater) {
  // Duplicated from Component.
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

問題在于為什么要造一個ComponentDummy
我的理解是如果為了繼承prototype的話下面沒必要再用assign再設(shè)置一遍方法,他既然用了繼承了,這邊注釋說為了避免方法額外的原型查找才用的assign,既然這樣的話寫成下面這樣不就好了嗎

var pureComponentPrototype = PureComponent.prototype;
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
回答
編輯回答
赱丅呿

PR里面有一個跟你一樣的想法。鏈接在這里。

首先你的想法是完全正確的。為什么不這么做的。我們看Dan的猜測。Dan說可能是因為IE8不支持Object.assign吧。為了兼容老用戶。不想一下子升上來拋棄掉他們。

但是他也不是很確定。于是他@sebmarkbage。sebmarkbage算是補充。就算有了Object.assign。其他人用了polyfills。但是也無法保證polyfills是否是標(biāo)準(zhǔn)的??赡苡行┤藭靡恍┓菢?biāo)準(zhǔn)的實現(xiàn)就會出問題。所以還是不改這里比較穩(wěn)。

2017年10月6日 14:29
編輯回答
萌小萌

本來要找兩次現(xiàn)在把方法提了一級只找一次
圖片描述

2018年4月29日 22:10