All files / libs/lang hasOwnEnumProp.js

100% Statements 6/6
100% Branches 4/4
100% Functions 1/1
100% Lines 5/5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                1x                           1x     94x       81x   81x    
/**
 * @module      libs/lang/hasOwnEnumProp
 * @createdAt   2016-07-01
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
var isObject = require('./isObject')
 
/**
 * 判断 obj 对象是否含有某个 key,且 key 需要 enumerable ( 利用 getOwnPropertyDescriptor )
 *
 * 另外也可以使用 Object.prototype.propertyIsEnumerable.call(obj, key)
 *
 * @param   {Object} obj
 * @param   {String} key
 * @return  {Boolean}
 *
 * @author  Zhonglei Qiu
 * @since   2.0.0
 */
module.exports = function(obj, key) {
  // 如果不做判断 node v0.12 会报 TypeError: Object.getOwnPropertyDescriptor called on non-object
  // 但高版本的都不会报错
  if (!isObject(obj)) return false
 
  // https://github.com/sindresorhus/dot-prop/issues/23
  // 可以过滤掉原生的像 hasOwnProperty 这样的 key
  var descriptor = Object.getOwnPropertyDescriptor(obj, key)
 
  return !!(descriptor && descriptor.enumerable)
}