Home  >  Article  >  Web Front-end  >  How to determine whether a JS object has a certain attribute

How to determine whether a JS object has a certain attribute

高洛峰
高洛峰Original
2017-02-08 17:29:001034browse

Whether the JS object has a certain attribute

Two methods, but slightly different

1, in operator

var obj = {name:'jack'};
alert('name' in obj); // --> true
alert('toString' in obj); // --> true

It can be seen that whether it is name or toString on the prototype chain, it can be detected and returned true.

2. hasOwnProperty method

var obj = {name:'jack'};
obj.hasOwnProperty('name'); // --> true
obj.hasOwnProperty('toString'); // --> false

The properties inherited from the prototype chain cannot be detected by hasOwnProperty and return false.

It should be noted that although in can detect the properties of the prototype chain, for in usually cannot.

Of course, after rewriting the prototype, for in will be visible under IE9/Firefox/Safari/Chrome/Opera. See: Defects of for in

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more related articles on how to determine whether a JS object has a certain attribute, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn