underscore源码学习(1)

316 阅读1分钟

在underscore中,isArguments是这样定义的:

// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
  _['is' + name] = function(obj) {
    return toString.call(obj) === '[object ' + name + ']';
  };
});

// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
  _.isArguments = function(obj) {
    return _.has(obj, 'callee');
  };
}
  • 怎么理解在IE9以下,这段代码呢?
if (!_.isArguments(arguments)) {
  _.isArguments = function(obj) {
    return _.has(obj, 'callee');
  };
}

答:_.has(obj, 'callee')等价于Object.hasOwnproperty.call(obj, 'callee')。而我们知道Arguments类型有一个callee属性,其他数据类型没有,所以可以根据这个来判断Arguments类型。

  • 又引出了另一个问题,为什么不直接用这个callee来判断呢,为什么前面还要先用toString判断一下呢?

答:因为在严格模式下,第5版 ECMAScript (ES5) 禁止使用 arguments.callee()。