Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript】详解Object.prototype.hasOwnProperty() #3

Open
Lydever opened this issue Dec 12, 2021 · 0 comments
Open

【JavaScript】详解Object.prototype.hasOwnProperty() #3

Lydever opened this issue Dec 12, 2021 · 0 comments

Comments

@Lydever
Copy link
Owner

Lydever commented Dec 12, 2021

Object.prototype.hasOwnProperty()

hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。用通俗的话来说就是:用来判断一个属性是定义在对象本身而不是继承自原型链的。

语法

obj.hasOwnProperty(prop)
  • prop
    要检测的属性的 String 字符串形式表示的名称,或者 Symbol。
  • 返回值
    用来判断某个对象是否含有指定的属性的布尔值 Boolean。

实例

const obj = {};
obj.property1 = 88;

console.log(obj.hasOwnProperty('property1'));  // true

console.log(obj.hasOwnProperty('toString'));  // false

console.log(obj.hasOwnProperty('hasOwnProperty')); // false

注意: 即使属性的值是 null undefined,只要属性存在,hasOwnProperty 依旧会返回 true

o = new Object();
o.lisi = null;
o.hasOwnProperty('lisi'); // 返回 true
o.lizi = undefined;
o.hasOwnProperty('lizi'); // 返回 true

使用 hasOwnProperty 方法判断属性是否存在
下面的例子检测了对象 o 是否含有自身属性 prop:

o = new Object();
o.hasOwnProperty('prop'); // 返回 false
o.prop = 'exists';
o.hasOwnProperty('prop'); // 返回 true
delete o.prop;
o.hasOwnProperty('prop'); // 返回 false

自身属性与继承属性
下面的例子演示了 hasOwnProperty 方法对待自身属性和继承属性的区别:

o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // 返回 true
o.hasOwnProperty('toString');         // 返回 false
o.hasOwnProperty('hasOwnProperty');   // 返回 false

使用 hasOwnProperty 作为属性名
JavaScript 并没有保护 hasOwnProperty 这个属性名,所以就会出现设置hasOwnProperty为函数名的情况:

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

那么,在使用:

foo.hasOwnProperty('bar'); // 始终返回 false

为解决这种情况,可以使用下面这两种方式:

// 1. 可以直接使用原型链上真正的 hasOwnProperty 方法
({}).hasOwnProperty.call(foo, 'bar'); // true

// 2. 使用 Object 原型上的 hasOwnProperty 属性
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

==注意==,只有在最后一种情况下,才不会新建任何对象。

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant