React Navigation源代码阅读 : utils/invariant.js

'use strict';

/**
 * 该模块用于提供一个断言函数 invariant(),用于帮助你的程序断言某些应该为 true 的状态条件。
 * 
 * 使用方式和 sprintf 类似,只是通配符只支持 %s,如果断言条件不为true,则会抛出一个 Error。 
 *
 */

var validateFormat = function(format) {};

if (__DEV__) {
  validateFormat = function(format) {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }
  };
}

/**
 * 判断断言条件表达式是否为true,如果不为true,则抛出 Error
 * @param condition 断言条件表达式
 * @param format 断言条件不为真时抛出的错误的消息的模版,可以包含通配符%s
 * @param a...f 用于组织错误消息的参数
 */
function invariant(condition, format, a, b, c, d, e, f) {
  validateFormat(format);

  if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error(
      'Minified exception occurred; use the non-minified dev environment ' 
      + 'for the full error message and additional helpful warnings.'
      );
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        })
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}

module.exports = invariant;

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/80244205