This article mainly introduces two methods to determine whether a JS object has a certain attribute. If you need it, you can refer to the two methods, but there are some differences.
1, in Operator
The Code is as follows:
Var obj = {name: 'jack '};
Alert ('name' in obj); // --> true
Alert ('tostring' in obj); // --> true
We can see that both the name and the toString on the prototype chain can detect that the return value is true.
2. hasOwnProperty Method
The Code is as follows:
Var obj = {name: 'jack '};
Obj. hasOwnProperty ('name'); // --> true
Obj. hasOwnProperty ('tostring'); // --> false
Attributes inherited from the prototype chain cannot be detected through hasOwnProperty. false is returned.
It should be noted that, although in can detect the attributes of the prototype chain, for in usually does not work.
Of course, after the prototype is rewritten, for in is visible under IE9/Firefox/Safari/Chrome/Opera. See: for in defects