I was looking for a way to check if an object is a FormData instance, similarly to Array.isArray()
-
what is the question here?hackerrdave– hackerrdave2017-09-11 00:04:02 +00:00Commented Sep 11, 2017 at 0:04
-
Possible duplicate of What is the instanceof operator in JavaScript?hackerrdave– hackerrdave2017-09-11 00:05:29 +00:00Commented Sep 11, 2017 at 0:05
-
@hackerrdave how to detect if a JavaScript object is an instance of FormDatakm6– km62017-09-11 00:05:43 +00:00Commented Sep 11, 2017 at 0:05
-
1@km6—then perhaps that question should be in the text of your question somewhere.RobG– RobG2017-09-11 00:55:42 +00:00Commented Sep 11, 2017 at 0:55
2 Answers
Use instanceof
For example:
let formData = new FormData()
let time = new Date()
console.log("statement: formData is a FormData instance", formData instanceof FormData) // statement is true
console.log("statement: time is a FormData instance", time instanceof FormData) // statment is false
2 Comments
instanceof, it should have been presented as an answer explaining how instanceof could solve my problem - which is exactly what I did in my own response. At the time of posting, I wasn't aware of instanceof, and that was the message I intended to convey in my original post. I didn't dismissinstanceof.Here is the best alternative to instanceof. Unlike instanceof this works even if the FormData object was instantiated in another global environment such as a different window or frame:
function isFormData(value) {
try {
var test = (new FormData).has,// Throws in old browsers
isFormData = test.call(value,0) || true;// Throws if not a FormData instance
}
catch(e) {
// if browser is too old, use Object.prototype.toString test
isFormData = !test && {}.toString.call(value)=='[object FormData]'
}
return isFormData
}
This function works because FormData.prototype.has will throw if it's called on any value that isn't a FormData object. A Object.prototype.toString test is used as a backup if browser is too old. The Object.prototype.toString test by itself is one of the best tests that there is as well if you're looking for more brevity in your code and cross browser compatibility.
This answer is similar to Bergi's answer on the question How to reliably check an object is an EcmaScript 6 Map/Set?