Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 17:11:06
Original
1170 people have browsed it

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template