5.18 has

5.18.1 语法

_.has(object, key)

5.18.2 说明

如果object包含key,返回true 作用等同于于object.hasOwnProperty(key)

5.18.3 代码示例

示例一:基本用法

_.has({a: 1, b: 2}, 'b'); //=> true
_.has({a: 1, b: 2}, 'c'); //=> false

示例二:也可以检测函数

var obj = {
    foo: 'bar',
    func: function() {}
};
_.has(obj, 'func'); //=> true

5.18.4 不检测原型链上的属性

function Func(){
    this.name = 'moe';
}

Func.prototype.age = 10;

var func = new Func();
_.has(func, 'name'); //=> true;

//原型链上的增加的属性
_.has(func, 'age'); //=> false;

5.18.5 如想检测原型链上的属性用in

function Func(){
    this.name = 'moe';
}
Func.prototype.age = 10;

var func = new Func();
console.log('age' in func); //=> true
console.log(func.hasOwnProperty('age')); //=> false

5.18.6 检测null或undefined

_.has(null, 'foo'); //=> false;
_.has(undefined, 'foo'); //=> false;

5.18.7 源码展示

_.has = function(obj, key) {
    //如果存在obj, 返回obj.hasOwnProperty(key)
    return obj != null && hasOwnProperty.call(obj, key);
};

5.18.8 我们为什么不这么写?

function has(obj, key) {
    //这种写法有bug,得采用call的方式
    return obj != null && obj.hasOwnProperty(key);
};

//下面是测试
var foo = {
    hasOwnProperty: function() {
        return false;
    },
    bar: 'Here be dragons'
};
//这不是我们想要的
has(foo, 'bar'); //=> false

5.18.9 参考网址

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty