Skip to content

公共方法

util.deprecate(fn , msg)

标记当前 fn 是一个不应该被调用的函数,如果调用了就警告一次,但是还是执行的

js
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
	// 如果是 node环境  那么直接使用node内置的 deprecate方法
	if (isUndefined(global.process)) {
		return function() {
			return exports.deprecate(fn, msg).apply(this, arguments);
		};
	}
  // 如果设置了 noDeprecation 那么就不发出警告
	if (process.noDeprecation === true) {
		return fn;
	}

  // 警告一次的标记位
	var warned = false;
  // 使用函数柯里化生成高阶函数,保存原来的 fn 和 msg
	function deprecated() {
    // 如果没有提示过
		if (!warned) {
      // 显示警告信息
			if (process.throwDeprecation) {
				throw new Error(msg);
			} else if (process.traceDeprecation) {
				console.trace(msg);
			} else {
				console.error(msg);
			}
			warned = true;
		}
    // 执行回调
		return fn.apply(this, arguments);
	}

	return deprecated;
};