>>> var jq = $('body');
>>> var di = {hello: 'world'};
>>> typeof jq == typeof di;
true
This is not true :(. a dict object and a jquery object aren't the same type. Is t开发者_开发百科his sort of thing possible with javascript?
The typeof both variables is Object
. I think you are going for instanceof
.
jq instanceof jQuery // -> true
di instanceof jQuery // -> false
use jQuery.isPlainObject
jQuery.isPlainObject(di) === true
jQuery.isPlainObject(jq) === false
Why do you need to tell the difference? I've found that it's better to think about this problem from the other direction: in the immediate circumstance where you have an object of unknown provenance, what are the different possibilities? In other words, can it really be anything, or is it just that you need to know what method to call?
It's a matter of personal preference, but generally I find it easier to do duck-typing checks more loosely, and just check to see if a couple of "signal" properties are present on the mystery object.
精彩评论