typeof undefined. Which is faster and better?
This question already has an answer here:
If you are looking for a way to check member existence, you should use in operator
if ("b" in a) {
...
}
The error c is not defined raised, because c is not defined anywhere in the program.
What typeof ab will return, is the type of data which is stored in ab . What if b actually exists and it actually holds the value undefined ? Both typeof ab and !ab will evaluate to a truthy value. So, they should not be used for member existence checks.
Please check this answer to know why in should be preferred for member existence.
I would use the in operator
if ('b' in a) {
...
}
I'd use it because it was done exactly for checking if a property exists in an object, and because it's much more readable than the others (IMO).
However, it doesn't matter which one is faster because you'd be microoptimizing (unless you that operation millions or billions of times).
Cheers
PS: c is not defined happens because with cb you tried to acces the b member of an undefined variable ( c )
I'm not sure what you're trying to achieve but there are two problems. The first part is checking for a property being defined in an object. The first if is checking if the type of the property is defined or not but it could be "undefined" on purpose.
Use to check if the object has the property.
if(b.hasOwnProperty("c")) {
}
If you want to "lookup" for the property in the whole prototype chain then use in :
if ("c" in b) {
}
Otherwise checking of bc is "undefined" means that the value returned by "bc" is of type "undefined". It doesn't mean that b has or doesn't have the property "c".
The second block is failing because "c" isn't defined in the global scope. You cannot access a property of an undefined object which will cause an error.
note
If you don't have prototype chains, hasOwnProperty should be faster in most cases.
链接地址: http://www.djcxy.com/p/27320.html