Created
April 30, 2011 07:00
-
-
Save rkatic/949493 to your computer and use it in GitHub Desktop.
isArguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cross-browser but not absolutely strong. | |
function isArguments( obj ) { | |
return typeof obj === "object" && ( "callee" in obj ) && typeof obj.length === "number"; | |
} | |
// Ideally strong, but broken on Opera... | |
var isArguments = (function( undefined ) { | |
var toStr = ({}).toString, | |
returnTrue = function() { | |
// To be sure it will not be inlined (future engines). | |
return arguments !== undefined; | |
}, | |
test = function( obj ) { | |
return obj != null && toStr.call( obj ) === "[object Arguments]"; | |
}; | |
return test( arguments ) ? test : | |
function( obj ) { | |
// Using "in" works in strict mode too. | |
if ( obj != null && "callee" in obj ) { | |
try { | |
return returnTrue.apply( this, obj ); | |
} catch (e) {} | |
} | |
return false; | |
}; | |
})(); |
For three reasons:
- The global
undefined
can be redefined. It's just a variable as another. - It's bit faster because one scope closer to the usage scope.
- Minifiing, "undefined" becomes only one letter long.
Oh yes, I understand that. I thought it had some other relevance to the function.
What are the benefits of the closure and extra function calls? Isn't this basically the same:
var isArguments = function(obj) {
var cls = Object.prototype.toString.call(obj);
if (cls == "[object Arguments]") {
return true;
} else if (obj != null && "callee" in obj) {
try {
return (function() {
return arguments !== undefined;
}).apply(this, obj);
} catch (e) {}
}
return false;
};
Yes, it's basically the same. Just slower, mainly because of the function definition on every run..
Makes sense. Nice work!
Just note that your versions will fail with null or undefined values, so you should do obj != null
as first check.
Yeah I forgot to put that in there on my initial post, but I added it in right afterwards. Doh!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very smart using .apply as a final test for object as array! My only question is why the "undefined" argument to the first function?