Home  >  Article  >  Web Front-end  >  Two ways to determine whether a JS object has a certain attribute_javascript skills

Two ways to determine whether a JS object has a certain attribute_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:11:061131browse

Two ways, but slightly different

1, in operator

Copy code The code is as follows:

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

You can see that both name and toString on the prototype chain can be detected and return true.

2, hasOwnProperty method

Copy code The code is as follows:

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

The properties inherited on 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 is visible under IE9/Firefox/Safari/Chrome/Opera. See: Defects of for in

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